Vuex核心概念示例

Mutation

  1. 触发mutations的第一种方式:
    1. this.$store.commit('add')
    2. commit 的作用,就是调用某个 mutations 函数。

//定义Mutations
export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    add(state){
      state.count++
    },
    addN(state, step){
      state.count += step
    }
  }
})

//触发mutations
methods: {
    btnAdd(){
      // 触发mutations的第一种方式,通过commit调用mutations中的add函数
      this.$store.commit('add')
    },
    btnAddN(){
        this.$store.commit('add', 3) //触发 mutations 时传递参数
    }
}

2. 触发mutations的第二种方式:

//1.从vuex中按需导入 mapMutations 函数
import {mapMutations} from 'vuex'
//2.通过mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法。
methods: {
    ...mapMutations(['add', 'addN'])
}

Action

  1. 触发 actions 的第一种方式:
    1. this.$store.dispatch('addAsync')
    2. 触发 actions 异步任务时携带参数
//定义 Action
export default new Vuex.Store({
  mutations: {
    add(state){
      state.count++
    },
    addN(state, step){
      state.count += step
    }
  },
  //在 actions 中不能直接修改 state 中的数据,
  //还是要通过触发 mutations 的方式间接变更数据
  actions: {
      addAsync(context){
          setTimeout(()=>{
              context.commit('add')
          }, 1000)
      },
      addNAsync(context, step){
          setTimeout(()=>{
              context.commit('addN', step)
          }, 1000)
      }
  }
})
//触发 Action
methods: {
    handle(){
        this.$store.dispatch('addAsync') //触发 actions 的第一种方式
    }
    handle2(){
        this.$store.dispatch('addNAsync', step)
    }
}
  1. 触发 actions 的第二种方式:
<template>
//通过mapActions函数,将actions函数,映射为当前组件的methods方法,
//所以,subAsync就变成了methods中的函数,可以直接在template中使用。
    <button @click="subAsync">-1 Async</button>
    <button @click="subNAsync(5)">-N Async</button>
</template>

//1.从vuex中按需导入 mapActions 函数
import {mapActions} from 'vuex'
//2.通过mapActions函数,将需要的actions函数,映射为当前组件的methods方法。
methods: {
    ...mapActions(['subAsync', 'subNAsync'])
}

Getter

 

//定义 Getter
export default new Vuex.store({
    state: {
        count: 0
    },
    getters: {
        showNum: state => {
            return `当前最新数量是[${state.count}]`
        }
    }
})

//使用 getters 的第一种方式
this.$store.getters.showNum
//<h3>当前最新的count值:{{$store.state.count}}</h3>
<h3>{{$store.getters.showNum}}</h3>

//使用 getters 的第二种方式
import {mapGetters} from 'vuex'
methods: {
    ...mapGetters(['showNum'])
}
//<h3>当前最新的count值:{{count}}</h3>
<h3>{{showNum()}}</h3>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值