vuex状态管理:具体介绍随时查官网简介
- state:类似于在实例data中定义一个变量
- getter:有点像计算属性computed.接受state作为第一个参数
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
]
},
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
})
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
- mutation:类似实例的methods中定义的方法
//定义
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
//调用
store.commit('increment')//count = 2
//还可以传入额外的参数(载荷方式)
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})//count = 11
- action:类似于mutation,但是action相当于提交mutation,并且最重要的是它可以包含异步操作
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
increment (context) {
context.commit('increment')
}
}
})
//这样调用action的方法(action同样支持载荷方式)
store.dispatch('increment')
- module:我理解的就是在状态管理中内容比较复杂和多的时候,将这些内容分割为模块(module).
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态
每个模块内部的mutation和getter,接收的第一个参数为模块的局部对象
- 命名空间namespace:Boolean,是一个比较重要的概念,添加这行代码后,该模块内部的所有 getter、action 及 mutation 会根据模块的层级自动调整命名
const store = new Vuex.Store({
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']
}
}
}
}
}
})
- 其他还有一些概念以及注意事项,在官网上解释的更为详尽