vue中 vuex 的使用
npm install vuex --save // 安装
$store.state.XXX
this.$store.commit('XXX')
this.$store.dispatch('XXX')
import { mapState,mapMutations,mapActions } from 'vuex'
...mapState(['XXX'])computed
...mapMutations(['XXX'])methods
...mapActions(['XXX'])methods
const store = new Vuex.Store({ state: { //用于存放全局变量 count: 0 //** 定义一个全局变量 }, mutations: { //用于变更store中的数据,可以监控所有数据的变化 add(state) { //注册一个函数,传入的第一个参数必须为 state ,后面的参数可以是传入的值,例:(state,step) state.count++ //** state. } }, actions: { //用于异步执行mutations中的函数 addAsync(context) { //注册一个函数,传入的第一个参数必须为 context ,后面的参数是传入的值,例:(context,step) setTimeout(() => { context.commit('add') //** context.commit(' ')//传入的参数再传到mutation 中使用,例:('add',step) },1000) } }, modules: { } })
state:
所有共享数据都要统一放到store的state中进行存储
1)使用state中的数据: $store.state.count
2)在需要使用state数据的vue文件中,从vuex中导入 mapState 函数:
import { mapState } from 'vuex'
将需要使用的数据映射为当前组件的 computed 计算属性:
export default {
computed:{
...mapState(['count'])// ...是展开运算符,表示把这些数据映射为当前组件的一个计算属性,函数里面放一个数组,放入需要使用的数据,然后就可以直接在组件中使用数据名称调用了
}
}
mutations:
只能通过mutation变更state中的数据
1)使用mutation中的函数:this.$store.commit('add')//可以在后面再传入参数,例:('add',3)
2)在需要使用mutation中函数的vue文件中,从vuex中导入 mapMutations 函数:
import { mapMutations } from 'vuex'
将需要使用的函数映射为当前组件的 methods 方法:
export default {
methods:{
...mapMutations(['add']),//数组里放需要使用的方法,然后就可以在其他方法中调用这个方法了,直接用用 this. 来调用
handButton(){
this.add();//可以给它传值,例:('add',3)
},
}
}
actions:
用于处理异步任务
1)触发sctions中的异步操作:this.$store.dispatch('addAsync')//可以在后面再传入参数,例:('addAsync',3)
2)在需要使用actions中函数的vue文件中,从vuex中导入 mapActions 函数:
import { mapActions } from 'vuex'
将需要使用的函数映射为当前组件的 methods 方法:
export default {
methods:{
...mapActions(['addAsync']),//数组里放需要使用的方法,然后就可以在其他方法中调用这个方法了,直接用用 this. 来调用
handButton(){
this.add();//可以给它传值,例:('addAsync',3)
},
}
}
posted on 2021-03-26 10:55 cropsecrab 阅读(114) 评论(0) 收藏 举报
浙公网安备 33010602011771号