本文摘自PHP中文网,作者青灯夜游,侵删。
如果你之前使用过vue.js,你一定知道在vue中各个组件之间传值的痛苦,在vue中我们可以使用vuex来保存我们需要管理的状态值,下面我们就来看一下vuex中常用的一些知识点,希望对大家有一定的帮助。
一、为什么要使用Vuex
1、多个组件依赖同一个状态,使用组件之间通信方法会非常繁琐,例如多层嵌套组件。
2、需要全局保存的数据,例如用户、权限信息,全局系统设置
二、Vuex的五个核心属性
1、state:存储状态
2、getters:state作为第一个参数,其他getters作第二个参数,返回值会根据他的依赖缓存起来,相当于Vue的计算属性
1 2 3 4 5 6 7 8 9 10 | state: {
count: 1,
sum: 2
},
getters: {
getCountAndSum: (state,getters) => {
return state.count + state.sum;
}
}});
|
3、mutations:修改状态(同步的),state 作为第一个参数,提交载荷作为第二个参数
1 2 3 4 5 6 7 8 9 | const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state, obj) {
state.count += obj.n;
}
}});
|
4、actions:异步操作(执行mutations的方法,不是直变更状态)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
increment (state, obj) {
state.count += obj.n;
}
},
actions: {
increment (context) {
context.commit( 'increment' );
}
}});
|
5、modules:store的子模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | const a = {
state: {
count: 0
},
getters: {
getCount2 (state, getters, rootState) {
return state.count + 2;
}
},
mutations: {
increment (state, getters, rootState) {
state.count++;
}
},
actions: {
increment (context) {
context.commit( 'increment' );
}
}};const b = {};const store = new Vuex.Store({
modules: {
a,
b }});
|
三、Vuex辅助函数
阅读剩余部分
相关阅读 >>
bootstrap和vue的区别
4个很 nice 的vue router过渡动效,快来收藏!
vue.nexttick是什么
如何解决vue中layui报错问题
vue 和 react 的优点有哪些
vue如何给组件加css样式
怎么运行vue.js
vue.怎么绑定属性
ant design支持vue吗
eclipse支持vue吗
更多相关阅读请进入《vue》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » Vuex中常用知识点(总结)