一、介绍
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
二、安装vuex
npm install vuex --save
三、vuex的使用
vuex的核心是state,他是一个容器,里面放的是应用的状态,vuex和基本的全局对象的不同是:vuex的状态存储是响应式的,不能直接改变state的状态,只能通过commit调用mutation里面的方法改变:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
})
四、vuex的核心
1、state存放状态,在组件里获取状态使用this.$store.state获取,count是state里面的属性名,也可以使用辅助函数mapstate,
computed: {
count () {
return this.$store.state.count
}
}
import { mapState} from 'vuex'
export default {
computed: {
localComputed () { /* ... */ },
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
}
2.getter是 store 的计算属性,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。接受state作为第一个参数,通过this.$store.getters调用,也可以使用辅助函数mapgetters将 store 中的 getter 映射到局部计算属性
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
3.mutation类似于事件,可以改变state的状态,必须同步操作,在组件中改变状态时通过this.$store.commit('事件名',传递的参数)调用mutation里面的事件
this.$store.commit('increment', 10)
4.action和mutation类似,只不过action提交的是mutation,包含异步操作,action通过this.$store.dispatch()调用
this.$store.dispatch('increment')
5.module可以将store分割成不同的模板,每个模板里面包含state、getter、mutation、action。
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 的状态
总结:
到这里,我的介绍就完了,祝你生活愉快