vuex状态管理的使用
文章目录
1.起步
1.安装vuex
npm install vuex --save
2.在src目录新创建一个js文件用于vuex,然后在该目录下引入vuex,如下:
import Vue from 'vue'
import Vuex from 'vuex'
//注意:记得使用下面这句
Vue.use(Vuex)
3.vuex基本代码结构
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
})
2.访问全局状态
1.直接通过this.$store.state.count–(但是不能直接用这个对全局状态进行修改,否则很麻烦,访问是可以的)如下图:
2.通过mapState函数
2.1mapState函数访问:
1.导入mapState函数
import { mapState } from ‘vuex’2.将全局数据映射为当前组件的计算属性
computed:{
------- “…” :为三元运算符
…mapState([‘count’])
}
3.访问方式:可以直接在组组件中访问,相当于count变成了data中的属性一样
如下图:
3.通过Mutation修改全局状态
好处是可以集中监听数据的变化
下面是使用方式:
3.1触发mutations函数的第一种方法
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
//即通过下面这个函数进行全局状态的更改,只要外面的组件访问到这个方法就可以了
increment (state) {
// 变更状态
state.count++
}
}
})
组件中调用increment的方法:
通过this.$store.commit('increment')即可调用,该段代码可以写到一个methods中。
如下图:
注意:如果要携带参数的话直接在commit函数中加入参数即可,如:this.$store.commit(‘increment’,param)即可。记得store中的函数也要加一个参数。
3.2触发mutations函数的第二种方法
1.在组件中 导入 mapMutations 函数:
import { mapMutations } from ‘vuex’
通过该函数将需要的store中的函数映射为当前组件的methods方法
2.使用方法如下:
methods: {
…mapMutations([‘increment’]) //increment:为store中的函数
}
即可将increment函数映射为当前组件的函数,直接this.increment()就可以访问了。
具体如下图:
4.使用action处理store中函数的异步调用
注意:mutations中不能写异步函数的代码
使用方式:通过在action中触发mutation的方式间接变更数据
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
addAsync(context){
setTimeout(
()=>{
// 通过context间接触发commit函数 只能在action中执行异步操作
context.commit('add')
},1000
)
}
}
})
触发actions中函数的方式:
1.触发actions函数的第一种方式:
this.$store.dispatch('addAsync')
2.触发actions函数的第二种方式:
导入mapActions函数
import { mapActions } from 'vuex'
将指定的actions函数映射为当前组件的methods函数
methods: {
...mapActions(['addAsync'])
}
3.提供带参数的调用
param:即为传递的参数
asyncFunction(context,param){
setTimeout(()=>{
context.commit('increment',param)
},3000)
}
this.$store.dispatch('asyncFunction',2)
具体如下:
视频看到12集