概念
专为vue项目开发的状态管理模式。采用集中式存贮管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式改变。
- state,驱动应用的数据源;
- view,以声明方式将 state 映射到视图;
- actions,响应在 view 上的用户输入导致的状态变化。
特点
1. 响应式
状态改变驱动组件高效更新,反之亦然。
2. 唯一的状态修改途径 提交mutation
// 如果在模块化构建系统中,请确保在开头调用了 Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
store.commit('increment')
console.log(store.state.count) // -> 1
- 通过 store.state 来获取状态对象
- 通过 store.commit 方法触发状态变更
State
Vuex 使用单一状态树——是的,用一个对象就包含了全部的应用层级状态。至此它便作为一个唯一数据源。
vue组件中获取vuex状态
- 计算属性中将某个状态返回
计算属性为初始化vue对象时传入的computed属性的值
// 创建一个 Counter 组件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return store.state.count
}
}
}
store.state.count 变化的时候, 都会重新求取计算属性,并且触发更新相关联的 DOM。
- 将状态从根组件注入到每一个子组件
需调用Vue.use(Vuex)
const app = new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
components: { Counter },
template: `
<div class="app">
<counter></counter>
</div>
`
})
注册完成后,子组件能够通过this.$store访问到父组件的状态。
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
mapState状态优化辅助函数
当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性。
也就是计算属性·中的一个函数,作用是2一次操作多个计算属性。
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
当映射的计算属性的名称与 state 的子节点名称相同时,我们也可以给 mapState 传一个字符串数组。
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
使用建议
单个状态严格属于某组件时作为组件的局部状态,否则将可复用的状态放入vuex。
Getter
可用于过滤多个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)
}
}
})
Getter 接受 state 作为其第一个参数。
通过属性访问getter
store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]
组件中使用
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
通过方法访问
你也可以通过让 getter 返回一个函数,来实现给 getter 传参。
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
Mutation
更改 Vuex 的 store 中的状态的唯一方法是提交mutation。
禁止异步操作。每个 mutation 都有一个字符串的 事件类型 (type) 和 一个回调函数(handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受state作为第一个参数。
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state) {
// 变更状态
state.count++
}
}
})
要唤醒一个 mutation handler,你需要以相应的 type 调用 store.commit 方法:
store.commit('increment')
Payload
通过store.commit 传入额外的参数,即 mutation 的 载荷
// ...
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)
Mutation 必须是同步函数。
Action
- 支持异步,用于解决Mutation不可异步的问题。
- Action 提交的是 mutation,而不是直接变更状态。
触发方式
store.dispatch('increment').then(() => {
// ...
})
使用async/await
// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
严格模式
使 Vuex store 进入严格模式,在严格模式下,任何 mutation 处理函数以外修改 Vuex state 都会抛出错误。
const store = new Vuex.Store({
// ...
strict: true
})