
正文
vuex - 辅助函数学习
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
官网文档:
https://vuex.vuejs.org/zh-cn/api.html 最底部
mapState
此函数返回一个对象,生成计算属性 - 当一个组件需要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。mapState可以声明多个
需要在组件中引入:
import { mapState } from 'vuex'
...mapState({ // ... }) 对象展开运算符
mapGetters
将store中的多个getter映射到局部组件的计算属性中
组件中引入
import { mapGetters } from 'vuex'
组件的 computed 计算属性中使用
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
或者给getter属性另起个名字:
mapGetters({
doneCount: 'doneTodosCount'
})
mapMutations
将组件中的 methods 映射为 store.commit 调用(需要在根节点注入store)。
组件中引入:
import { mapMutations } from 'vuex'
组件的 methods 中使用:两种方式,传参字符串数组或者对象,
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
mapActions
将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):
组件中引入:
import { mapActions } from 'vuex'
组件的 methods 中使用:两种方式,传参字符串数组或者对象,
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
2018-04-07 17:57:31







