Vuex的自我修养

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小小的理解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值