什么是vuex
如果不打算开发大型单页应用,应用够简单,最好不要使用 Vuex。一个简单的 store 模式就足够了。但是,如果需要构建一个中大型单页应用,就要考虑如何更好地在组件外部管理状态,Vuex 是不错的选择。
vuex的使用
在 Vue 的单页面应用中使用,需要使用Vue.use(Vuex)调用插件。将其注入到Vue根实例中。
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
getter: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
},
mutations: {
increment (state, payload) {
state.count++
}
},
actions: {
addCount(context) {
// 可以包含异步操作
// context 是一个与 store 实例具有相同方法和属性的 context 对象
}
}
})
// 注入到根实例
new Vue({
el: '#app',
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
store,
template: '<App/>',
components: { App }
})
然后改变状态:
this.$store.commit('increment')
核心
State,Getter,Mutation,Action,Module,
Vuex 主要有四部分:
1.state:包含了store中存储的各个状态。
2.getter: 类似于 Vue 中的计算属性,根据其他 getter 或 state 计算返回值。
3.mutation: 一组方法,是改变store中状态的执行者,只能是同步操作。
4.action: 一组方法,其中可以包含异步操作。
State
Vuex 使用 state 来存储应用中需要共享的状态。为了能让 Vue 组件在 state更改后也随着更改,需要基于state 创建计算属性。
// 创建一个 Counter 组件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count // count 为某个状态
}
}
}
Getter
类似于 Vue 中的 计算属性(可以认为是 store 的计算属性),getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
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 会暴露为 store.getters 对象,可以以属性的形式访问这些值:
store.getters.doneTodos // -> [{ id: 1, text: ‘…’, done: true }]
Getter 方法也接受 state和其他getters作为前两个参数。
getters: {
// ...
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
store.getters.doneTodosCount // -> 1
我们可以很容易地在任何组件中使用它:
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
注意: getter 在通过属性访问时是作为 Vue 的响应式系统的一部分缓存其中的。