一.state的基础使用方法:
1.直接使用
2.使用计算属性
3.使用mapState
二.mutation使用方法,修改state的值
1.使用commit提交
1.1无参提交
1.2带有参数的
1.2.1普通参数
1.2.2 payload参数荷载
使用:
getPayLoad(){ // way1: // this.$store.commit('changeCountPayload',{count:80}) // way2: this.$store.commit({ type: 'changeCountPayload', count:10, }) },
2.使用mapMutations
1.引入mapMutations,按需引入,需要哪个引入哪个
import { mapMutations,mapState,mapActions,mapGetters} from 'vuex'
2.定义mutations中的方法
mutations:{ edit(state,payload){ state.name = payload.name console.log(payload) // 15或{age:15,sex:'男'} }, addN(state,step){ state.step=step } }
3.在methods中使用:
放在mapMutations中的方法可以使用this.方法名调用,该传参的需要传递参数
methods:{ ...mapMutations(['edit','addN']), editN(){ this.edit({name:'mapMutations'}) } }
放在mapMutations中的方法可以直接添加到标签里面使用,相当于this.方法名
<div @click="edit({name:'mapMutations'})">{{count}}</div>
三.actions,异步请求,要改的state需要提交给mutations
actions需要 context.commit()提交state变量到mutations,methods里面使用时,dispatch触发
mutations:{ edit(state,payload){ state.name = payload.name console.log(payload) // 15或{age:15,sex:'男'} }, addN(state,step){ state.step=step } }, actions:{ // 两种使用方法调用。 aEdit(context,payload){ setTimeout(()=>{ context.commit('edit',payload) },2000) }, // 带有传参的 addNasync(context,step){ setTimeout(()=>{ context.commit('addN',step) }) } },
1.dispatch触发:
expend(){ // this.$store.dispatch('aEdit',{name:15}) this.$store.dispatch('addNasync','44-step') }
2.使用mapActions
1.引入mapActions
import { mapMutations,mapState,mapActions,mapGetters} from 'vuex'
使用:
methods:{ ...mapMutations(['edit','addN']), editN(){ this.edit({name:'mapMutations'}) } }
getters使用:
getters:{ nameInfo(state){ return "姓名:"+state.count }, fullInfo(state,getters){ return getters.nameInfo+'年龄:'+state.type } },
使用:
方法1:直接获取
<div>{{this.$store.getters.fullInfo}}</div>
方法二:mapGetters,同上需要引入mapGetters
computed:{ ...mapGetters(['fullInfo']) }
使用:
<p>{{fullInfo}}</p>
vuex模块化开发:
1.创建一个独立文件,存放各模块的数据,例如a.js
a.js的代码:重点属性nameSpaced,添加namespaced:true的方式使其成为带命名空间的模块。(160条消息) Vuex 命名空间 namespaced 介绍_扛麻袋的少年的博客-CSDN博客
export default { namespaced: true, actions: {}, mutations: {}, state:{ mount:'111' }, getters: {}, };
导入到index.js中,
index.js代码:
import Vue from "vue"; import Vuex from "vuex"; import ModuleA from "./modules/a" Vue.use(Vuex); export default new Vuex.Store({ modules: { ModuleA } });