1、概念
vuex是集中式存储管理应用中的所有组件的状态,并以相应的规则来保证状态以可预测的方式发生变化。
复制代码
2、属性
1、state——> 状态、数据,可以通过this.$store.state获取;
//mutations\actions的区别
2、mutations——> 更新状态的函数,可以通过this.$store.commit('方法名')提交mutations中的方法来更改状
态,只能是同步的,专注于修改state的状态;
3、actions——> 不能直接修改state,通过提交mutation来实现,可以包含异步操作,通过
this.$store.dispatch('方法名')分发action
4、getters——> 从基础数据上派生的,相当于state的计算属性
5、modules——> 模块,每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块
复制代码
3、创建store下的js文件
// 在项目的src文件夹下面创建store文件夹,在store下创建index.js
import Vue from 'vue'
import Vuex from 'vuex'
// 启用vuex
Vue.use(Vuex)
// 声明vuex实例对象,创建四个对象属性
export default new Vuex.Store({
state: {
state: { counter:0 },
},
mutations: {
add(state) {
state.counter++
}
},
actions: {
add({ commit }) {
setTimeout(() => {
commit('add')
}, 1000);
}
},
getters: {
doubleCounter(state) { // 计算剩余数量
return state.counter * 2;
}
}
})
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END