Vuex 是一个专为 Vue.js 应用程序开发的全局状态管理工具,用于任意组件之间进行通信。 它有以下几个核心部分组成: state:存储数据; mutations:用于变更state中的数据; actions:调用mutations方法,处理异步任务; getters:对Store中已有的数据进行加工处理形成新的数据,Store中数据发生变化,Getters的数据也会跟着变化。
Vuex官方文档
组件访问State中的数据的方式: 第一种:this.$store.state.全局数据名称 第二种方法:mapState映射函数
//第一步,在组件中导入mapState函数 import {mapState} from 'vuex' //第二步,通过mapState函数将当前组件需要的全局数据映射为当前组件的computed计算属性 //该属性就可以直接使用了例如<div>{{myDate}}</div> computed:{ ...mapState(['myDate']); }(1). 只能通过mutations变更Store数据,不可以使用this.$store.state.全局数据名称= 啥啥啥的方式直接操作Store中的数据。 (2). 通过mutations变更Store数据虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化。 (3). mutations里不能编写异步代码
//实例: //定义Mutation const store = new Vuex.Store({ state: {count: o}, mutations: { //变更状态函数 add(state){ state.count++ } //外界可传参的变更状态函数,第二参数表示外界传入的参数 change(state,step){ state.count+=step } } }) //************************************* //在组件中调用变更状态函数第一种方法 methods:{ handle1(){ //触发mutations中的状态变更函数 this.$store.commit('add'); }, handle2(){ //触发mutations中的状态变更函数,携带参数 this.$store.commit('change',3); } } //************************************* //在组件中调用变更状态函数第二种方法 //第一步,在组件中导入mapMutations函数 import{mapMutations} from 'vuex' //第二步:通过mapMutations函数将当前组件需要的mutations函数映射为当前组件的methods方法 methods:{ ...mapMutations(['add','change']), handle1(){ this.add(); }, handle2(){ this.change(3); } }Actions 用于处理异步任务,不能直接修改State中的数据,需要调用mutations里的状态变更函数
//定义Action const store = new Vuex.Store ({ state: {count: o}, mutations: { add(state){ state.count++; }, sub(state,step){ state.count -= step; } }, actions: { addAsync(context){ setTimeout(()=> { context.commit( 'add' ); }, 1000) }, subAsync(context,step){ setTimeout(()=> { context.commit( 'sub',step ); }, 1000) } } }) //*********************************************** methods:{ handle1(){ //触发Action的第一种方式 this.$store.dispatch ('addAsync'); }, handle1(){ //触发Action的第一种方式 //带参数 this.$store.dispatch ('subAsync',step); } } //*********************************************** //触发Action的第二种方式 //第一步,在组件中导入mapActions函数 import{mapActions} from 'vuex' //第二步:通过mapActions函数将当前组件需要的actions函数映射为当前组件的methods方法 methods:{ ...mapActions(['addAsync','subAsync']), handle1(){ this.addAsync(); }, handle2(){ this.subAsync(3); } }对全局数据可以进行分模块管理。
import Vue from 'vue' import Vuex from 'vuex' import app from './modules/app' import user from './modules/user' Vue.use(Vuex) const store = new Vuex.Store({ modules: { app, user } }) export default store //当前文件夹下modules/app.js const app = { state:{ }, mutations:{ }, actions:{ } , getters:{ } } export default app //当前文件夹下modules/user.js const user= { state:{ }, mutations:{ }, actions:{ } , getters:{ } } export default user对vuex模块的数据操作
//对模块的state this.$store.state.模块名.全局数据名称 或者 computed:{ ...mapState('模块名',['全局数据名称']); } //对模块的Mutations this.$store.commit('模块名/方法名'); 或者 computed:{ ...mapMutations('模块名',['方法名']); } //对模块的Actions this.$store.dispatch ('模块名/方法名'); 或者 computed:{ ...mapActions('模块名',['方法名']); } //对模块的getters this.$store.getters.模块名.名称 或者 computed:{ ...mapGetters('模块名',['名称']); }vuex面试题汇总
