VUX

本文详细介绍了Vue.js中状态管理工具Vuex的使用方法,包括mapState、mapGetters、mapMutations及mapActions等核心API的应用场景和具体实现方式,并通过实例展示了如何通过dispatch进行异步操作。

1.mapState

 2.mapGetters

 3.

4.

 当你的操作行为中含有异步操作,比如向后台发送请求获取数据,就需要使用action的dispatch去完成。
其他使用commit即可。

 

举个例子:

const store = new Vuex.Store({
  state: {
    count: 10,
    numb: 10086
  },
  getters: {
    add: (state) => {
      return state.count;
    },
  },
  mutations: {
    increment(state,val) {
      if(val){
        state.count += val;
      }else{
        state.count += 2;
      }

    },
  },
  actions: {
    actionA({dispatch, commit}) {
      return commit('add');
    },
    increment({commit}) {
      return commit('increment')
    }
  }
});


/* eslint-disable no-new */
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app-box')

 

使用:

import {mapState,mapActions,mapMutations,mapGetters} from 'vuex'

 

 methods:{
    ...mapMutations({addNumber:'increment'}),
    increment(){
      this.$store.dispatch('increment');
    }
  },
  computed: {
    ...mapState({count:'numb'}),
    ...mapGetters(['add'])
  },

 

 <div class="hello">
      <button @click="increment">加+2{{count}}</button>
    </div>
    <div class="hello">
      <button @click="addNumber(5)">加+5{{count}}</button>
    </div>
    <div class="hello">
      <button >{{add}}</button>
    </div>

 

点击+2:store的count+=2

点击+5:store的count+=5

...mapState({count:'numb'}),
意思是this.count=this.$store.state.numb

...mapMutations({addNumber:'increment'}),
意思是之行this的addNumber函数的时候,执行this.$store的mutations的increment的函数

 

转载于:https://www.cnblogs.com/hualuoshuijia/p/7798685.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值