天天看點

vuex mapActions使用案例解析

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    msg:"Hello Vuex!",
    name:"cxj",
    age:18,
    hobby:"美女"
  },
  getters: {
    tenYearsOld(state){
      return state.age + 10;
    },
  },
  mutations: {
    changeMsg(state,payload){
      console.log("changeMsg mutations");
      state.msg = payload;
    }
  },
  actions: {
    getMsg({commit},msg){
      console.log("changeMsg actions");
      setTimeout(() => {
        commit("changeMsg",msg)
      }, 2000);
    }
  },
  modules: {
  }
})
           

App.vue

<template>
  <div id="app">
    {{msg}}
    <hr />
    <button @click="asyncChangeMsg">點我改變msg-async</button>
    <br />
    <button @click="masyncChangeMsg('Hello vuex! mapActions')">點我改變msg-async-mapActions</button>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";

/*
Action 類似于 mutation,不同在于:Action 送出的是 mutation,而不是直接變更狀态(避免異步帶來的狀态混亂);Action 可以包
含任意異步操作。

在元件中使用 this.$store.dispatch('xxx') 分發 action,或者使用 mapActions 輔助函數将元件的 methods 映射為 
store.dispatch 調用(需要先在根節點注入 store)
*/
export default {
  name: "App",
  components: {},
  computed: {
    ...mapState(["msg", "name", "age"])
  },
  methods: {
    ...mapActions({
      masyncChangeMsg: "getMsg"
    }),
    asyncChangeMsg() {
      this.$store.dispatch("getMsg", "Hello vuex! dispatch");
    }
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
           

效果截圖-dispatch:

vuex mapActions使用案例解析

效果截圖-mapActions:

vuex mapActions使用案例解析