前提分类:
- 单一状态树中使用
- 模块化中使用
一:单一状态树中使用
- mapState使用
import { mapState } from 'vuex'
// 四种方式
computed: {
// 1.数组形式,映射的计算属性的名称与 state 的子节点名称相同
...mapState(['testState'])
// 2.对象形式 - 箭头函数
...mapState({
count: state => state.count,
})
// 3.对象形式 - state子节点名(箭头函数的简写方式)
...mapState({
countAlias: 'count',
})
// 4.对象形式 - 普通函数(可以使用计算属性中其他的属性值)
...mapState({
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
- mapGetters辅助函数
import { mapGetters } from 'vuex'
computed: {
// 1.与mapState的方式1一致
...mapGetters([
'doneTodosCount'
])
// 2.与mapState的方式3一致
...mapGetters({
doneCount: 'doneTodosCount'
})
}
- mapMutations辅助函数
import { mapMutations } from 'vuex'
methods: {
// 1.与mapState的方式1一致
...mapMutations([
'increment'
])
// 2.与mapState的方式3一致
...mapMutations({
add: 'increment'
})
}
- mapActions辅助函数
import { mapActions } from 'vuex'
methods: {
// 1.与mapState的方式1一致
...mapActions([
'increment'
])
// 2.与mapState的方式3一致
...mapActions({
add: 'increment'
})
}
二:模块化中使用
- mapState辅助函数
import { mapState } from 'vuex'
computed: {
// 与单一状态树相比增加了参数1-所属模块名,其他一致。(下同)
// user为某个模块名,根据实际情况修改
// 与单一状态树四个方法类似
// 方法1
...mapState('user', ['testState'])
// 方法2
...mapState('user', {
count: state => state.count,
})
// 方法3
...mapState('user', {
countAlias: 'count',
})
// 方法4
...mapState('user', {
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
或者(建议了解下):
// 使用 createNamespacedHelpers 创建基于某个命名空间辅助函数,简化mapState的写法
import { createNamespacedHelpers } from "vuex";
const { mapState } = createNamespacedHelpers("user");
computed: {
// 此时与单一状态树的写法完全一致(mapGetters/mapMutations/mapActions类似,不再赘述)
...mapState([
'testState'
])
// 单一状态树下的mapState的四个方法均可使用,这里不再赘述
...
}
- mapGetters辅助函数
import { mapGetters } from 'vuex'
computed: {
// 与mapState的方式1一致
...mapGetters('user',[
'doneTodosCount'
])
// 与mapState的方式3一致
...mapGetters('user',{
doneCount: 'doneTodosCount'
})
}
- mapMutations辅助函数
import { mapMutations } from 'vuex'
methods: {
// 与mapState的方式1一致
...mapMutations('user',[
'increment'
])
// 与mapState的方式3一致
...mapMutations('user',{
add: 'increment'
})
}
- mapActions辅助函数
import { mapActions } from 'vuex'
methods: {
// 与mapState的方式1一致
...mapActions('user',[
'increment'
])
// 与mapState的方式3一致
...mapActions('user',{
add: 'increment'
})
}









网友评论