该节教程代码可经过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
}
}
复制代码