官方解释:Vuex 是文让专为 vue.js 应用程序开发的状态管理模式。
什么是状态管理?
简单地讲:可以把多个组件都需要的变量全部存储到一个对象里面,然后这个对象放在顶层的满满 vue 实例中,让其他组件可以使用。文让这样多个组件就可以共享这个对象中的彻底所有属性。
有些同学想着,搞懂这么简单我们自己在vue顶层定义一个对象不就可以实现共享了?满满我们发现虽然数据可以获取到,但是文让如果在某个组件内,数据改变了,彻底那我们如何修改数据,搞懂让此数据在其他组件内保持最新呢?满满
我们的vuex就是为了提供一个在多个组件间共享状态的插件,而且能够实现实时响应。文让
vuex 是搞懂管理组件之间通信的一个插件,所以使用之前必须安装。
2.1、安装
1)使用 script 方式引入
<script src="https://cdn.bootcss.com/vuex/3.0.1/vuex.min.js"></script>2)使用包管理
npm install vuex --save //yarn add vuex注意:vuex 必须依赖 vue 使用
2.2、搭建 store 实例
创建一个 store 文件夹,新建 index.js
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex);//使用vuex export default new Vuex.Store({ state:{ }, mutations:{ }, getters:{ }, actions:{ }, modules:{ } })在 main.js 处,挂载 store
import store from ./store new Vue({ router, render: h=>h(App) }) //相当于 // Vue.prototype.$store = store2.3、亿华云计算使用状态
// store 中定义状态 state:{ statue: 在线 } //在组件内使用 <div>组件内数据:{ { $store.state.status }} </div> //在 js 中使用 mounted(){ console.log( this.$store.state.status ) }3.1、state
state 存放 vuex 的基本数据,用来存储变量的。
单一状态树
Vuex 使用单一状态树,即用一个对象就包含了全部的状态数据。state 作为构造器选项,定义了所有我们需要的基本状态参数。
在组件中引用 state 数据方式:
1)通过 vue 的 computed 获取 vuex 的 state
export default new Vuex.Store({ state:{ online:true } }) computed:{ status(){ return this.$store.state.online } }store 中的数据发生改变时,都会重新求取计算属性,并更新相关 DOM。
2)如果需要使用多个参数时,都使用 computed 计算属性,就会使代码变的有些冗余和复杂,此时我们就可以借助 mapState 辅助函数。
//state 中数据比较多,引用到一个组件内 export default new Vuex.Store({ state:{ online:true, per:[ { name:qq,age:18} ], role:管理员 } }) //组件内 import { mapState } from vuex export default { name: App, computed: mapState({ online: state => state.online, per: per, // per就相当于 state.per role: role // role就相当于 state.role }) }vuex 使用单一状态树来管理应用层级的全部状态,单一状态树能够让我们最直接的方式找到某个状态的片段,而且之后的维护和调试过程,也可以非常方便管理和维护。站群服务器
3.2、getters
从 store 中获取一些 state 变异后的状态。
使用的时候一般有两种方式:
1)返回的结果只依赖于 state 中的数据
export default new Vuex.Store({ state:{ count:2, }, getters:{ //返回 count 的 2 倍数据 countDouble(state){ return state.count*2 } } }) //组件中引用 <div> 获取countDouble:{ { $store.getters.countDouble }} </div> //运行结果 获取countDouble:4此处,$store.getters.countDouble 的使用与上边的 $store.state.count 是一样的。
2)getters 中返回的变异结果,依赖于某个 getters 中属性返回结果
export default new Vuex.Store({ state:{ count:2, }, getters:{ //返回 count 的 2 倍数据 countDouble( state ){ return state.count * 2 } //返回 countDouble 的 2 倍数据 countDoubleT( state , getters ){ return getters.countDouble * 2 } } }) //组件中引用 <div> 获取countDouble:{ { $store.getters.countDoubleT }} </div> //运行结果 获取countDouble:83.3、mutations
vuex 的store 状态的更新唯一方式:提交 Mutation。
Mutations 主要包括两部分:
字符串的事件类型
一个回调函数,该回调函数的第一个参数就是 state。
1)mutation 中的方法通过 commit 调用,不传参数使用:
export default new Vuex.Store({ state:{ count:2, }, mutations:{ incrs(state){ // count 加 1 state.count++ } } }) //组件调用 <button @click=" $store.commit(incrs) " >+</button> { { $store.state.count}}按钮每点一次,count 就会自加一次。
2)mutations 传递参数
我们点击加按钮时,指定每次点击增加的数值,亿华云如下:
export default new Vuex.Store({ state:{ count:2, }, mutations:{ addNum( state,n ){ // count 加 1 state.count +=n } } }) //组件调用 <button @click=" $store.addNum( incrs , 5 ) " >+</button> { { $store.state.count}} //运行结果 每点一次按钮,count 增加 5上个实例传递的是一个参数,如果我们需要传递多个参数时,该如何实现呢?
3)mutations 传递多个参数
export default new Vuex.Store({ state:{ count:2, }, mutations:{ addNum(state,payload){ // payload 是传递过来的参数对象 state.count += payload.count } } }) //组件调用 <button @click="addTen" >加10</button> { { $store.state.count}} export default{ methods:{ addTen(){ this.$store.commit({ type:addNum, count:10, ...//可以传任意多个参数 }) } } } //运行结果 每点一次按钮,count 增加 10上述方法是 mutations 特殊的提交封装。包含了 type 属性的对象,将整个 commit 的对象作为 payload 使用。
3.4、actions
mutations 提交更新数据的方法,必须是同步的,如果是异步使用就会出现问题,然后在项目开发中往往就会用到异步更新,比如网路请求数据。
actions 是类似于 mutation,功能大致相同,但是 actions 是用来替代 mutations 进行异步操作的。
1)actions 的基本使用
actions:{ aUpdateCount(context){ setTimeout(()=>{ //使用定时器模拟异步操作 context.commit(updateCount) },2000) } }, mutations:{ updateCount(state){ state.count = 5201314 }, } // 组件内使用 { { $store.state.count}} <button @click="$store.dispatch(aUpdateCount)">异步更新count</button> //运行结果 点击按钮,两秒后更新 count 值为5201314值得注意的是,使用 actions 异步更新数据的时候,还是需要经过 mutations 中的方法,state 中的数据只能由 mutations 中的方法修改。
调用 mutations 中的方法,使用 commit 调用。
调用 actions 中的方法,使用 dispatch 调用。
2)异步更新的时候,也可以带参数
// 功能:点击按钮,指定 count 修改的值 actions:{ aUpdateCount( context, payload ){ setTimeout(()=>{ //使用定时器模拟异步操作 context.commit( updateCount , payload ) },2000) } }, mutations:{ updateCount( state , payload ){ state.count = payload }, } // 组件内使用 { { $store.state.count}} <button @click="$store.dispatch( aUpdateCount, 我爱前端 )">异步更新count</button> //运行结果 点击按钮,两秒后更新 count 值为: 我爱前端3)传入异步参数
actions:{ //传入promise updateData(context,payload){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(我学会了) },2000) }) }, } //组件内调用 <button @click="ok">promise执行成功,返回"我学会了"</button> methods:{ ok(){ this.$store.dispatch(updateData).then((res)=>{ console.log(res) }) }, } //运行结果 点击按钮,两秒后打印:我学会了3.5、modules
modules 是模块的意思,vue 使用单一状态树,项目越来越大,store 中的数据越来越多,不便于数据的管理和维护,代码也会变得臃肿。因此使用 modules ,把数据划分到对应的某个模块,既便于开发,也提高代码的可读性。
1)modules 简单使用
import Vue from vue import Vuex from vuex import { Increase } from ./mutation_type.js Vue.use(Vuex) export default new Vuex.Store({ state: { }, actions: { }, getters: { }, mutations: { }, modules:{ a:{ state:{ }, getters:{ }, mutations:{ }, actions:{ } }, b:{ state:{ }, getters:{ }, mutations:{ }, actions:{ } } }, }) //也可以整理为 const moduleA = { state:{ }, getters:{ }, mutations:{ }, actions:{ } } const moduleB = { state:{ }, getters:{ }, mutations:{ }, actions:{ } } Vue.use(Vuex) export default new Vuex.Store({ state: { }, actions: { }, getters: { }, mutations: { }, modules:{ a: moduleA, b: moduleB }, })2)模块中的数据如何使用呢?
const moduleA = { state:{ aName:我是模块a的数据 }, getters:{ }, mutations:{ }, actions:{ } } // 组件内引用 { { $store.state.a.aName }}3)调用模块内的 mutations 中的方法,如何调用呢?
$store.commit(aChangeName)调取模块内的 mutations 中的方法,与之前是一模一样的,程序会先从第一层 store 中查找方法,找不到方法时会继续去模块中查找。
4)调用模块内的 getters 内方法
$store.getters.getName需要注意的是,getters 中方法都是对 state 中数据变异,如果模块的 getters 方法需要根 store 中的 state 呢?
getName(state,getters , rootState){ // state 表示当前模块的 state // getters表示当前模块的getters //rootState 表示根 store 内的state }5)模块内的 actions 中的方法,使用 commit 调用 mutations 中方法时,只能调用本模块内的 mutations 方法,不能调用外层的。
Vuex 的 store 中的 state 是响应式的,当 state 中数据发生改变时,vue 组件会自动更新。这就要求我们必须遵守一些vuex对应的规则:
提前在 store 中初始化好所需的属性。
说人话,就是必须在state中定义的属性才能做到响应式,如果是后加或删除的,无法做到响应式。
举个栗子:
mutations:{ changeName(state){ state.info.name = 爱学习的前端人 }, addAdrs(state){ state.info[address] = "陕西西安" }, } { { this.$store.state.info}} <button @click="$store.commit(changeName)">修改姓名</button> <button @click="$store.commit(addAdrs)">增加地址</button>此时点击修改姓名的时候,可以做到响应式,而点击“增加地址”按钮时,页面没有任何反应,但是在开发者模式中可以看到数据有变化。
我们要响应式,该如何实现呢?
addAdrs(state){ state.info[address] = "陕西西安" //修改为: Vue.set(state.info,address,陕西西安) },同样的如果要删除 age 属性时,使用 delete 也做不到响应式,需要修改为 Vue.delete。
实例:响应式删除 age 属性
deleteAge(state){ //delete state.info.age //修改为 Vue.delete(state.info,age) }, //组件内容 { { this.$store.state.info}} <button @click="$store.commit(deleteAge)">删除年龄</button>在 mutation 中定义很多事件类型,也就是方法名。当项目越来越大时,Vuex 管理的状态越来越多,需要更新状态的情况越来越多,那么意为着 Mutations 中的方法名越来越多,方法过多时,使用的时候需要花费大量精力去记住或来回切换文件找方法名,这样很容易出错,所以推荐大家使用一个常量,即使方法名出错了,也会将错就错,程序并不会发生异常。
如:
// 新建 mutation_type.js 文件 //导出一个常量 export const Increase = increase // store.js文件 import Vue from vue import Vuex from vuex import { Increase } from ./mutation_type.js Vue.use(Vuex) export default new Vuex.Store({ state:{ count:2, }, mutations:{ [Increase](state){ state.count++ }, } }) //组件内容 { { $store.state.count }} <button @click="add">加10</button> import { Increase } from ./store/mutation_type sxport default{ methods:{ add(){ this.$store.commit(Increase) } } }使用的时候,只需要记住 Increase 或者在 mutation_type.js 文件内查找就好了。