什么是vuex?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
安装
-
npm
npm i vuex@next -S -
yarn
yarn add vuex@next -S
在 vue3 中导入 vuex
-
创建 ./store/index.js
import { createStore } from 'vuex' const store = createStore({ }) export default store; -
在 main.js 中引入
import { createApp } from "vue"; import App from "./App.vue"; import store from "./store/index.js"; const app = createApp(App); app.use(store) app.mount("#app");
state
Vuex使用单一状态树,每一个应用仅仅包含一个 store 实例,可以让我们能够直接地定位给任一特定的状态片段(方便调试),存储在 Vuex 中的数据与 Vue 实例中的 data 遵循相同的规则。
定义 state
const store = createStore({
state:{
count:100
}
})
在其他地方获取 state 中的数据
export default {
data(){
return {
// 注意我们不能在 data 中用 this 去获取数据,因为当 data 函数执行的时候才会给 this 添加对应的属性
count: $store.state.count // 100
}
}
}
在 computed 计算属性中获取数据
export default {
computed: {
count () {
return this.$store.state.count
}
}
}
mapState 辅助函数
当一个组件需要获取多个状态的时候,这些重复性的声明会导致计算属性有些重复和冗余。为了解决这一问题,我们可以使用官方提供的 mapState 这个函数帮助我们生成计算属性。
mapState 这个函数支持两种格式的传参,一种是数组形式,一种是对象形式。
export default {
computed: {
mapState([])
}
}
Mutation
Mutation 是更改 Vuex 中的 store 中的状态的唯一方法,它类似于事件。每一个 mutation 都有一个字符串的 事件类型(type)和回调函数(handler),且这个回调函数会接受 state 作为第一个参数,且可以传入额外的参数作为 mutation 的载荷(payload)。
基本使用
const store = createStore({
state:{
count:100
},
mutation:{
countAdd(state,value){
state.count += value
}
}
})
用常量代替 Mutation 的事件类型
// test.js
export const COUNT_ADD = 'countAdd'
import { COUNT_ADD } from './mutation-types'
const store = createStore({
state:{
count:100
},
mutation:{
// ES2015 的计算属性命名功能
[COUNT_ADD](state,value){
state.count += value
}
}
})
Mutation 中的 handler 必须是一个同步函数,如果 mutation 是一个异步函数,那么我们的 devtools 将会无法知晓这个回调函数在何时被调用——即任何在回调函数中进行的状态更改时无法被我们给捕获的。
普通调用 Mutation
export default {
methods:{
countAdd(){
// 通过这个函数去调用 mutation 中的回调函数
this.$store.commit('xxx')
}
}
}
使用 mapMutations 映射调用
export default {
methods:{
// 数组形式
...mapMutations(['increment'])
// 会将 this.increment() 映射成 this.$store.commit('increment')
// 对象形式
...mapMutations({
add:'increment'
// 将 this.add() 映射成 this.$store.add('increment')
})
}
}
Getter
store 的计算属性,Getter 接受 state 作为其中第一个参数,接受其他 getter 作为第二个参数
基本使用
const store = createStore({
state:{
count:100
},
getters:{
// 通过属性访问
doubleCount(state,getter){
return state.count * 2;
}
// 通过方法访问
testCount(state,getter){
return (value)=>{
return state.count*value;
}
}
// 或者
testCount:(state,getter)=>(value)=>{
return state.count*value;
}
}
})
调用 getter 属性
export default {
methods:{
testCount(value){
return this.$store.getters.
}
}
}
通过 mapGetters 映射
export default {
computed(){
// 数组形式映射
...mapGetters(['doubleCount','testCount'])
// 对象形式映射,可以给 getters 自定义名称
...mapGetters({
doubleCount:'doubleCount',
test:'testCount'
})
}
}
Action
Action 类似于 mutation,但是有两个不同:
- Action 提交的是 mutation,而不是直接变更 state
- Action 可以包含任意的异步操作
Action 函数接受一个与 store 实例具有相同方法,因此我们可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getter。
基本使用
const store = createStore({
state: {
count: 0
},
mutation:{
addCount(state,payload){
state.count+=payload.value
}
},
action:{
addCount(context){
context.commit('addCount')
},
// 通过参数解构来简化代码
addCount({ commit },obj){
commit('addCount',{
value:obj.value
})
}
}
})
分发 Action
// 以载荷形式分发
this.$store.dispatch('addCount',{
value:100
})
// 以对象形式分发
this.$store.dispatch({
type:'addCount',
value:10
})
使用 mapAction 映射
export default {
methods: {
// 数组形式
...mapActions([
'addCount', // 将 `this.addCount()` 映射为 `this.$store.dispatch('addCount')`
]),
// 对象形式
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('addCount')`
})
}
}
组合式 Action
// action 异步调用 addCount
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('addCount',1)
resolve()
}, 1000)
})
}
}
// 可以通过这个去调用异步函数
this.$store.dispatch('actionA').then(() => {
// ...
})
// 配合 async/await
// 假设 test1() 和 test2() 返回的都是 promise
action:{
async actionA({commit}){
commit("test1",await test1())
},
async actionB({dispath,commit}){
await dispatch('actionA') //等待 actionA 完成
commit('test2',await test())
}
}
// 一个 store.dispatch 在不同模块中可以触发多个 action 函数。
// 在这种情况下,只有当所有触发函数完成后,返回的 Promise 才会执行。
Module
由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己独立的,store,mutation,action,getter,module
const moduleA = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: () => ({ ... }),
mutations: { ... },
actions: { ... }
}
const store = createStore({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
模块的局部状态
对于模块内部的 mutation 和 getter,接受的第一个参数是模块的局部状态对象。对于模块内部的 action,局部状态通过 context.state 暴露出来,根节点的状态则为 context.rootState,对于模块内部的 getter,根节点状态会作为第三个节点暴露出来:
const moduleA = {
state: () => ({
count: 0
}),
mutations: {
increment (state) {
// 这里的 `state` 对象是模块的局部状态
state.count++
}
},
getters: {
// 根节点状态
doubleCount (state,getters,rootState) {
return state.count * 2
}
},
actions: {
incrementIfOddOnRootSum ({ state, commit, rootState }) {
if ((state.count + rootState.count) % 2 === 1) {
commit('increment')
}
}
}
}
命名空间
在默认情况下,模块内部的 action 和 mutation 仍然是注册在全局命名空间中的——这样使得多个模块能够对同一个 action 和 mutation 做出响应,Getter 同样也默认注册在全局命名空间。必须注意,不要再不同的,无命名空间的模块中定义两个相同的 getter。
const store = createStore({
state:{
count:0
},
mutations:{
addCount(state,value){
state.count+=value
}
},
getters:{
doubleCount(state){
return state.count*2;
}
},
actions:{
actionAddCount({commit},value){
commit('addCount',value)
}
},
modules:{
moduleA:{
mutations: {
test(state, value) {
// 调用全局命名空间中的 addCount
store.commit('addCount', value)
}
}
}
}
})
如果希望模块有更高的封装度和复用性,我们可以通过 namespace:true 的方式使其成为带命名空间的模块。当模块被注册的时候,它所有的 getter,action,mutation 都会根据模块注册的路径调整命名。
const store = createStore({
modules: {
account: {
namespaced: true,
// 模块内容(module assets)
state: () => ({ ... }), // 模块内的状态已经是嵌套的了,使用 `namespaced` 属性不会对其产生影响
getters: {
isAdmin () { ... } // -> getters['account/isAdmin']
},
actions: {
login () { ... } // -> dispatch('account/login')
},
mutations: {
login () { ... } // -> commit('account/login')
},
// 嵌套模块
modules: {
// 继承父模块的命名空间
myPage: {
state: () => ({ ... }),
getters: {
profile () { ... } // -> getters['account/profile']
}
},
// 进一步嵌套命名空间
posts: {
namespaced: true,
state: () => ({ ... }),
getters: {
popular () { ... } // -> getters['account/posts/popular']
}
}
}
}
}
})
启用了命名空间的 getter 和 action 会接受到局部化的 getter,dispatch 和 commit。
在带命名空间的模块内访问全局内容
如果我们希望使用全局的 state 和 getter,rootState 和 rootGetters 会作为第三和第四参数传入 getter,也会通过 context 对象的属性传入 action。如果我们需要在全局命名空间内分发 action 或提交 mutation,需要将 { root:true }作为第三个参数给 dispatch 或 commit 即可。
modules: {
moduleA: {
namespaced: true,
getters: {
// 在这个模块的 getter 中,`getters` 被局部化了
// 你可以使用 getter 的第四个参数来调用 `rootGetters`
someGetter (state, getters, rootState, rootGetters) {
getters.someOtherGetter // -> 'moduleA/someOtherGetter'
rootGetters.someOtherGetter // -> 'someOtherGetter'
rootGetters['bar/someOtherGetter'] // -> 'bar/someOtherGetter'
},
someOtherGetter: state => { ... }
},
actions: {
// 在这个模块中, dispatch 和 commit 也被局部化了
// 他们可以接受 `root` 属性以访问根 dispatch 或 commit
someAction ({ dispatch, commit, getters, rootGetters }) {
getters.someGetter // -> 'moduleA/someGetter'
rootGetters.someGetter // -> 'someGetter'
rootGetters['bar/someGetter'] // -> 'bar/someGetter'
dispatch('someOtherAction') // -> 'moduleA/someOtherAction'
dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'
commit('someMutation') // -> 'moduleA/someMutation'
commit('someMutation', null, { root: true }) // -> 'someMutation'
},
someOtherAction (ctx, payload) { ... }
}
}
}
在带命名空间的模块中全局注册 action
若需要在带命名空间的模块注册全局 action,你可添加 root: true,并将这个 action 的定义放在函数 handler 中。例如:
modules:{
moduleA:{
namespace:true,
action:{
test:{
root:true,
handler(context,payload){
}
}
}
}
}
带命名空间的绑定函数
当使用 mapState、mapGetters、mapActions 和 mapMutations 这些函数来绑定带命名空间的模块时,写起来可能比较繁琐,我们可以将模块的空间名称字符作为第一个参数上传给上述字符串,这样子所有的绑定,都会将该模块作为上下文
computed: {
...mapState({
a: state => state.some.nested.module.a,
b: state => state.some.nested.module.b
}),
...mapGetters([ 'some/nested/module/someGetter', // -> this['some/nested/module/someGetter']
'some/nested/module/someOtherGetter', // -> this['some/nested/module/someOtherGetter']
])
},
methods: {
...mapActions([ 'some/nested/module/foo', // -> this['some/nested/module/foo']()
'some/nested/module/bar' // -> this['some/nested/module/bar']()
])
}
// 简化为
computed: {
...mapState('some/nested/module', {
a: state => state.a,
b: state => state.b
}),
...mapGetters('some/nested/module', [ 'someGetter', // -> this.someGetter 'someOtherGetter', // -> this.someOtherGetter ])
},
methods: {
...mapActions('some/nested/module', [ 'foo', // -> this.foo() 'bar' // -> this.bar() ])
}
动态注册模块
在 store 创建之后,你可以使用 store.registerModule 方法注册模块:
import { createStore } from 'vuex'
const store = createStore({ /* 选项 */ })
// 注册模块 `a`
store.registerModule('a', {
// ...
})
// 注册嵌套模块 `a/a1`
store.registerModule(['a', 'a1'], {
// ...
})
我们可以通过 store.unregisterModule(moduleName) 去动态的卸载掉动态添加的模块,也可以使用store.hasModule(moduleName) 去查看该模块是否已经被注册到了 store,嵌套模块应该以数组的形式传递给如上函数,而不是路径字符串的形式传递。
保留 state
在注册一个新 module 时,你很有可能想保留过去的 state,例如从一个服务端渲染的应用保留 state。你可以通过 preserveState 选项将其归档:store.registerModule('a', module, { preserveState: true })。
当你设置 preserveState: true 时,该模块会被注册,action、mutation 和 getter 会被添加到 store 中,但是 state 不会。这里假设 store 的 state 已经包含了这个 module 的 state 并且你不希望将其覆写。