該節教程代碼可經過npm start運行devServer,在http://localhost:8080/查看效果vue
map映射函數 | 映射結果 |
---|---|
mapState | 將state映射到computed |
mapActions | 將actions映射到methods |
mapGetters | 將getters映射到computed |
代碼示例:/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
},
}
複製代碼
代碼示例:/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)
},
}
複製代碼
代碼示例:/lesson21/src/components/Index.vueui
在computed中添加count的映射:this
computed: {
...mapGetters(['count'])
}
複製代碼
等價於:
computed: {
count() {
return this.$store.getters.count
}
}
複製代碼