我有一个这样的 Vue 组件:
<script>
import { mapActions, mapGetters } from 'vuex'
export default {
props: ['index'],
computed: {
...mapGetters([
'type',
'width',
'height',
'description',
'smtTagMeasureUnits',
'tagValue'
])
}
</script>
<template>
<div :class='["block","module-"+type(index), "width"+width(index), "height"+height(index)]'>
<h3>{{ description(index) }}</h3>
<div class="data">
<h1>{{ tagValue(index) }}</h1>
<h2 class="measure">{{ smtTagMeasureUnits(index) }}</h2>
</div>
</div>
</template>
<style>
...
</style>
作为 prop 进入组件的参数 index 已成功传递给 getters:
getters: {
...
type: (state, getters) => (par) => {
return getters.widgetsConfig[par].type
},
width: (state, getters) => (par) => {
if (getters.widgetsConfig[par].width) {
return getters.widgetsConfig[par].width
} return 2
},
height: (state, getters) => (par) => {
if (getters.widgetsConfig[par].height) {
return getters.widgetsConfig[par].height
} return 1
},
...
}
工作正常,但我对这种代码风格不满意,因为 getterName(index)
在模板部分不断重复。我所有的 getter 都应该带有 index 作为 Prop ,所以我想在模板中只包含 getterName
并且在脚本部分中包含类似这样的内容:
...mapGetters([
'type',
'width',
'height',
'description',
'smtTagMeasureUnits',
'tagValue'
], index)
这里是否有可能实现代码风格的改进?
最佳答案
如果你想让事情保持干燥,那么利用将项目(index
对应的实体)信息获取到商店的逻辑是有意义的,因此组件只接收准备好被渲染。
建议的解决方案是创建一个 getter,它接受 index
作为参数并从 getters.widgetsConfig
返回完整的选项列表。
请注意,如果需要,可以重复使用其他 getter,以便将必要的信息收集到单个对象中。
可能的实现:
getters: {
...
getItemByIndex: (state, getters) => (index) => {
const { type, height, width } = getters.widgetsConfig[index]
return {
type,
height,
width
}
},
}
并更新组件以映射单个 getter 并在计算属性中使用它:
computed: {
...mapGetters([
'getItemByIndex'
]),
item () {
return this.getItemByIndex(index)
}
}
并且所有属性都可以通过 item.type
、item.height
、item.width
等在模板中访问。
关于javascript - 将参数传递给 Vuex 中的 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53289737/