1. 程式人生 > 實用技巧 >vuex入門(2)-輔助函式mapState和mapMutations

vuex入門(2)-輔助函式mapState和mapMutations

上一篇文章中,我們介紹了vuex的基本概念和使用方法
當需要共享的資料比較簡單且都是同步操作時,元件可以跳過Action,直接用 commit 方法呼叫Mutations
同時我們也可以藉助兩個輔助函式簡化我們的程式碼
mapState和mapMutations可以接收陣列或者物件作為引數
將store中的狀態對映到當前元件

一、mapState

獲取store中city變數的一般寫法為:

{{this.$store.state.city}}

我們可以在元件中引入mapState,將state對映到當前元件,簡化程式碼:

<script>
import { mapState } from 'vuex'
export default {
  name: ' ',
  computed: {
    ...mapState({
      // 將state中的city對映到當前元件中的currentCity
      currentCity: 'city'
    })
  }
}
</script>

在這種情況下,獲取city變數就可以這麼寫:

{{this.currentCity}}

二、mapMutations

元件通過commit方法呼叫mutation的一般寫法:

{{this.$store.commit('changeCity', city)}}

同理,我們可以引入mapMutations,簡化程式碼:

<script>
import { mapMutations } from 'vuex'
export default {
  name: ' ',
  methods: {
    handleCityClick (city) {
      this.changeCity(city)
    },
    // 將 state中的 changeCity對映到當前元件
    ...mapMutations(['changeCity'])
  }
}
</script>