VUE状态管理——store
管理全局变量,便于组件之间传值
一、创建文件
1、在store文件夹中新建index.js文件
import Vue from 'vue' //引入vue
import Vuex from 'vuex' //引入vue
//使用vuex
Vue.use(Vuex)
//创建Vuex实例
const store = new Vuex.Store({
state:{
count:1 //保存的数据
}
})
export default store //导出store
2、在main.js中引用文件,实例引入store对象
import store from ./store/index
new Vue({
store
})
二、State
数据保存在index.js文件中,可使用this.$store.state
来获取自定义数据
三、Getters
相当于vue中的computed计算属性,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。Getters 可以用于监听、state中的值的变化,返回计算后的结果
this.$store.getters.getStoreCount
//页面中这样写可直接调用getters中的方法
//index.js文件中定义getters的方法
const store = new Vuex.Store({
state:{
count:1
},
getters:{
getStoreCount:function(state){
return state.count+1;
}
}
})
四、Mutations
用来修改store中的值
//在页面的方法中调用mutation的方法
methos:{
addFun(){
this.$store.commit("add");
},
reductionFun(){
this.$store.commit("reduction");
}
}
在index.js文件中添加mutations
const store = new Vuex.Store({
state:{
count:1
},
getters:{
getStoreCount:function(state){
return state.count+1;
}
},
mutations:{
add(state){ //注意书写语法
state.count = state.count+1;
},
reduction(state){
state.count = state.count-1;
}
}
})
五、Action
虽然上述方法可以修改页面的值,但是官方并不建议这样做,我们可以使用action调用mutation改变状态的值
const store = new Vuex.Store({
state:{
count:1
},
getters:{
getStoreCount:function(state){
return state.count+1;
}
},
mutations:{
add(state){ //注意书写语法
state.count = state.count+1;
},
reduction(state){
state.count = state.count-1;
}
},
actions:{ //注册actions,类似vue里的mothods
addFun(context){ //接收一个与store实例具有相同方法属性的context对象
context.commit("add");
},
reductionFun(context){
context.commit("reduction");
}
}
})
页面的调用如下:
methos:{
addFun(){
this.$store.dispatch("addFun");
//this.$store.commit("add");
},
reductionFun(){
this.$store.dispatch("reductionFun");
//this.$store.commit("reduction");
}
}
若想传参也依次在调用的方法中加入即可
六、mapState、mapGetters、mapActions、mapMutations
可以使调用更加简洁,不用写很长
//vue文件中
//页面可直接使用自定义变量名{{conuNum}}表示
import {mapState, mapActions, mapGetters} from 'vuex'
computed:{
...mapState({
countNum: state=>state.count
})
}
//将 this.commonActionGet() 映射为 this.$store.dispatch('commonActionGet')
//这种写法方法名称必须对应
...mapActions(['commonActionGet', 'commonActionGetJSON'])
...mapActions({
'commonActionGet': 'commonActionGet',
'commonActionGetJSON': 'commonActionGetJSON'
})
七、总结
1、index.js 定义Vuex.Store
2、state 相当于数据库,定义了数据的结构和初始值
3、getters 获取state中的状态并返回,但是不能修改
4、actions 提交状态,调用mutations方法对数据进行操作
5、mutations 定义state数据的修改操作
6、mapState、mapGetters、mapActions、mapMutations 做映射