这篇文章主要介绍了vuex在项目中的使用情况,主要涉及了computed传参,getters传参以及mapGetters的替代方法。

getters传参

在getter返回的值套上一层函数就可以实现传参数

1
2
3
4
5
6
getPamType(state) { // 根据因素返回对应的数据类型
return (value) =>{
let item = state.factor.find(fItem => fItem.paramValue === value)
return item.paramType
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { mapGetters} from "vuex"

computed: {
...mapGetters('paramSetting', {
getPamType: "getPamType", // 注意这里引入getters中的方法
}),
pamType() { // computed传参
return (val) => {
return this.getPamType(val) // 使用getters中的方法
}
}
},

上面使用mapGetters获取getters,但是jest会报错,为了解决单元测试报错的问题可以换成以下写法:

vue计算属性computed方法内传参

1
2
3
4
5
pamType() {
return (val) => {
return this.getPamType(val)
}
}

VueX mapGetters 获取 Modules 中的Getters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const getters = {
dictFactor(state) {
return initDict(state.factor, {label: 'paramText', value: 'paramValue'})
},
dictCalcType(state) {
return initDict(state.calcType, {label: 'paramText', value: 'paramValue'})
},
getPamType(state) {
// if(!state.factor.length) return ''
return (value) =>{
let item = state.factor.find(fItem => fItem.paramValue === value)
return item && item.paramType
}
},
getCalcType(state) {
return (value) =>{
let item = state.calcType.find(fItem => fItem.paramValue === value)
return item && item.paramType
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
computed: {
...mapGetters('paramSetting', {
DICT_FACTOR: "dictFactor",
DICT_CALC_TYPE: "dictCalcType",
getPamType: "getPamType",
getCalcType: "getCalcType",
}),
pamType() {
return (val, type) => {
if(type) return this.getCalcType(val)
return this.getPamType(val)
}
}
},

上面是使用mapGetters获取getters中返回的值或方法,但是jest会报错
TypeError: Cannot read property 'paramSetting/' of undefined
为了解决上面的问题可以使用下面的方法:

computed: {
DICT_FACTOR() {
return this.$store.getters['paramSetting/dictFactor'] // 返回值
},
DICT_CALC_TYPE() {
return this.$store.getters['paramSetting/dictCalcType'] // 返回值
},
getPamType() {
return this.$store.getters['paramSetting/getPamType'] // 返回一个可传参的方法
},
getCalcType() {
return this.$store.getters['paramSetting/getCalcType'] // 返回一个可传参的方法
},
treeData() {
return this.$store.state.paramSetting.treeData
},
pamType() {
return (val, type) => {
if(!this.getCalcType || !this.getPamType) return // 注意这一行如果不写,jest仍然报错
// _this.getCalcType is not a function 所以还是tmd写上吧!!!
if(type) return this.getCalcType(val)
return this.getPamType(val)
}
}
},