如果你之前使用过vue.js,你一定知道在vue中各个组件之间传值的痛苦,在vue中我们可以使用vuex来保存我们需要管理的状态值,下面我们就来看一下vuex中常用的一些知识点,希望对大家有一定的帮助。
一、为什么要使用Vuex
1、多个组件依赖同一个状态,使用组件之间通信方法会非常繁琐,例如多层嵌套组件。
2、需要全局保存的数据,例如用户、权限信息,全局系统设置
立即学习“前端免费学习笔记(深入)”;
二、Vuex的五个核心属性
1、state:存储状态
// store.jsconst store = new Vuex.Store({ state: { count: 0 }});// 组件里获取count值$store.state.count
登录后复制
2、getters:state作为第一个参数,其他getters作第二个参数,返回值会根据他的依赖缓存起来,相当于Vue的计算属性
// store.jsconst store = new Vuex.Store({ state: { count: 1, sum: 2 }, getters: { getCountAndSum: (state,getters) => { return state.count + state.sum; } }});// 其他组件获取getter$store.getters.getCountAndSum
登录后复制
3、mutations:修改状态(同步的),state 作为第一个参数,提交载荷作为第二个参数
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state, obj) { state.count += obj.n; } }});// 其他组件调用mutations的方法$store.commit('increment', {n: 100});
登录后复制
4、actions:异步操作(执行mutations的方法,不是直变更状态)
const store = new Vuex.Store({ state: { count: 1 }, mutations: { increment (state, obj) { state.count += obj.n; } }, actions: { increment (context) { context.commit('increment'); } }});// 其他组件调用actions的方法$store.dispatch('increment');
登录后复制
5、modules:store的子模块
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.state.count; // context.rootState.count; context.commit('increment'); } }};const b = {};const store = new Vuex.Store({ modules: { a, b }});// 其他组件调用 (获取state的变量需要加上引入的module的别名)$store.state.a$store.state.b
登录后复制
三、Vuex辅助函数
import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'; export default { name: 'about', data () { return { count: 0, sum: 0 } }, computed: { ...mapState({ count: state => state.count, countAlias: 'count', countPlusLocalState (state) { return state.count + this.localCount; } }), ...mapGetters([ 'getCount', 'getSum' ]) }, mounted () { this.count = this.$store.state.count; this.sum = this.$store.state.a.sum; }, methods:{ ...mapMutations( 'add','addO' ), ...mapActions([ 'add','addO' ]), clickB () { this.$store.dispatch('add'); this.$store.dispatch('addO'); } }}count: {{count}}
getCount: {{$store.getters.getCount}}
sum: {{sum}}
getSum: {{$store.getters.getSum}}
登录后复制
相关推荐:2020年前端vue面试题大汇总(附答案)vue教程推荐:2020最新的5个vue.js视频教程精选
更多编程相关知识,请访问:编程入门!!
以上就是Vuex中常用知识点(总结)的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/3023242.html