Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
- 存储状态响应式
- 不能直接改变store中的状态,必须通过唯一方法commit去改变mutation
//vue.js
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
//index.js
this.$store.commit("increment")
复制代码
state
单一状态树,可以对应到组件中的data
获取状态方法
this.$store.state.count
复制代码
mapState 辅助函数
一个组件获取多个状态时候,用mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
//也可以简写成
count1,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
复制代码
对象展开运算符
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
复制代码
Getter
共享属性计算函数,对应组件中的component,接受state作为第一个参数,其他的getter作为第二个参数
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
复制代码
mapGetters 辅助函数
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
//如果想取另一个名字也支持
// doneCount: 'doneTodosCount'
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
复制代码
Mutation
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,state作为第一个参数
此外,mutation是辅助函数
提交载荷(Payload)
向 store.commit 传入额外的参数,即 mutation 的 载荷(payload):
//vuex
mutations: {
increment (state, n) {
state.count += n
}
}
//index
store.commit('increment', 10)
//******* 大多数情况下传入的是对象
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
//commit提交方式1
store.commit('increment', {
amount: 10
})
//提交方式2 建议
store.commit({
type: 'increment',
amount: 10
})
复制代码
在组件中提交mutation
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
复制代码
module
将store分割成模块,每个模块拥有stat、getter、mutation、action
const moduleA={
state:()=>({}),
mutation:{},
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 的状态
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END