阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里。
该节教程代码可通过npm start运行devServer,在http://localhost:8080/#/index查看效果
map映射函数
map映射函数 | 映射结果 |
---|---|
mapState | 将state映射到computed |
mapActions | 将actions映射到methods |
mapGetters | 将getters映射到computed |
mapState的使用
代码示例:/lesson21/src/components/Index.vue
首先需要引入map函数:
import { mapState, mapActions, mapGetters } from 'vuex'
在computed中使用mapState:
computed: {
...mapState(['a', 'b']),
}
就可以代替这段代码:
computed: {
a() {
return this.$store.state.a
},
b() {
return this.$store.state.b
},
}
mapActions的使用
代码示例:/lesson21/src/components/Index.vue
在methods中添加addA和addB的映射
methods: {
...mapActions(['addA', 'addB']),
},
等价于:
methods: {
addA(n) {
this.$store.dispatch('addA', n)
},
addB(n) {
this.$store.dispatch('addA', n)
},
}
mapGetters的使用
代码示例:/lesson21/src/components/Index.vue
在computed中添加count的映射:
computed: {
...mapGetters(['count'])
}
等价于:
computed: {
count() {
return this.$store.getters.count
}
}