Vue教程22:mapState、mapActions、mapGetters

閱讀更多系列文章請訪問個人GitHub博客,示例代碼請訪問這裏

該節教程代碼可經過npm start運行devServer,在http://localhost:8080/查看效果vue

map映射函數

map映射函數 映射結果
mapState 將state映射到computed
mapActions 將actions映射到methods
mapGetters 將getters映射到computed

mapState的使用

代碼示例:/lesson21/src/components/Index.vuegit

首先須要引入map函數:github

import { mapState, mapActions, mapGetters } from 'vuex'
複製代碼

在computed中使用mapState:vuex

computed: {
  ...mapState(['a', 'b']),
}
複製代碼

就能夠代替這段代碼:npm

computed: {
  a() {
    return this.$store.state.a
  },
  b() {
    return this.$store.state.b
  },
}
複製代碼

mapActions的使用

代碼示例:/lesson21/src/components/Index.vuebash

在methods中添加addA和addB的映射less

methods: {
  ...mapActions(['addA', 'addB']),
},
複製代碼

等價於:函數

methods: {
  addA(n) {
    this.$store.dispatch('addA', n)
  },
  addB(n) {
    this.$store.dispatch('addA', n)
  },
}
複製代碼

mapGetters的使用

代碼示例:/lesson21/src/components/Index.vueui

在computed中添加count的映射:this

computed: {
  ...mapGetters(['count'])
}
複製代碼

等價於:

computed: {
  count() {
    return this.$store.getters.count
  }
}
複製代碼
相關文章
相關標籤/搜索