这篇文章主要介绍了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", }), pamType() { return (val) => { return this.getPamType(val) } } }, 上面使用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) { 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 if(type) return this.getCalcType(val) return this.getPamType(val) } } },
|