vsh*_*hna 7 javascript vue.js vuex vuejs2
我有一个这样的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>
Run Code Online (Sandbox Code Playgroud)
参数index(作为prop进入组件)已成功传递给getter:
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
},
...
}
Run Code Online (Sandbox Code Playgroud)
效果很好,但是我对这种代码风格不满意,因为getterName(index)在模板部分不断重复。我所有的吸气剂都应带有索引作为道具,因此我想只getterName在模板中,而在脚本部分中这样:
...mapGetters([
'type',
'width',
'height',
'description',
'smtTagMeasureUnits',
'tagValue'
], index)
Run Code Online (Sandbox Code Playgroud)
是否可以在这里实现任何代码样式的改进?
aBi*_*uit 13
如果您想让事情保持干燥,那么利用将项目(index对应的实体)信息获取到商店的逻辑是有意义的,因此组件只接收准备好呈现的完整数据。
建议的解决方案是创建一个 getter,它接受index作为参数并从getters.widgetsConfig.
请注意,如果需要,可以重新使用其他 getter,以便将必要的信息收集到单个对象中。
可能的实现:
getters: {
...
getItemByIndex: (state, getters) => (index) => {
const { type, height, width } = getters.widgetsConfig[index]
return {
type,
height,
width
}
},
}
Run Code Online (Sandbox Code Playgroud)
并更新组件以映射单个 getter 并在计算属性中使用它:
computed: {
...mapGetters([
'getItemByIndex'
]),
item () {
return this.getItemByIndex(index)
}
}
Run Code Online (Sandbox Code Playgroud)
和所有的属性将通过一个模板内部触及item.type,item.height,item.width,等。
您始终可以创建返回 getter 结果的计算属性。就像是:
export default {
props: ['index'],
computed: {
...mapGetters([
'getTypeFromIndex',
'getWidthFromIndex',
'getHeightFromIndex'
]),
height(): { return this.getHeightFromIndex(index) },
width(): { return this.getWidthFromIndex(index) },
type(): { return this.getTypeFromIndex(index) },
//going a step further to clean up your templates...
classList: [
"block",
"height"+this.height,
"width"+this.width,
]
}
Run Code Online (Sandbox Code Playgroud)
这样你只需要height在你的模板中而不是height(index), 或者即使classList你走那么远
这也在此处引用:https : //github.com/vuejs/vuex/issues/688,我找不到它,但我知道我也看到了 Evan You 在 github 问题中推荐的内容。
| 归档时间: |
|
| 查看次数: |
2585 次 |
| 最近记录: |