Vuex是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。这官方表达非常难以理解,所以已实际的应用解释如何使用。
1.在项目文件夹src新建store文件夹-->store.js
引入vue以及vuex,创建定义变量count
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
count:5
}
});
在main.js中进行定义,就可以在项目中使用了
new Vue({
el: "#app",
router,
store,
components: { App },
template: "<App/>"
});
直接进行取值展示,使用插值表达式 {{ $store.state.count }} ,或者通过computed进行变量重新定义,也可以通过mapState进行批量定义变量count
通过引入 import { mapState } from 'vuex'
computed:{
count1(){
return this.$store.state.count
},
...mapState({
count2:'count'
})
},
2.定义getters中的getCount方法返回值,类型computed作用,自重state就是上面定义的state的状态集合对象
getters:{
getCount(state){
return state.count;
}
}
在单页面中插值表达式{{ $store.getters.getCount }},或者使用mapGetters进行批量定义
computed:{
count1(){
return this.$store.state.count
},
...mapState({
count2:'count'
}),
...mapGetters(['getCount'])
}
3.页面中添加加和减的按钮,并添加@click方法:add() 和del()
在store.js中定义mutations
mutations:{
addCount(state,num){
state.count += num;
},
delCount(state,num){
state.count -= num;
}
},
页面按钮点击操作事件,调用mutations中的函数:
methods:{
...mapMutations(['addCount','delCount']),
add(){
this.$store.commit('addCount',2);
},
del(){
this.$store.commit('delCount',1);
}
}
在store.js中定义actions的方法:通过提交调用mutations中的方法
actions:{
getAddCount(context,num){
context.commit('addCount',num);
},
getDelCount(context,num){
context.commit('delCount',num);
}
}
单页面引入,通过dispatch进行触发actions的函数,在通过commit的mutations中的方法改变count的状态值
<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex';
export default {
data(){
return {
}
},
computed:{
count1(){
return this.$store.state.count
},
...mapState({
count2:'count'
}),
...mapGetters(['getCount'])
},
methods:{
...mapMutations(['addCount','delCount']),
...mapActions(['getAddCount','getDelCount']),
add(){
// this.$store.commit('addCount',2);
this.$store.dispatch('getAddCount',2);
},
del(){
// this.$store.commit('delCount',1);
this.$store.dispatch('getDelCount',1);
}
}
}
</script>
一个简单的小例子,对vuex小小的理解