【发布时间】:2019-03-06 02:35:43
【问题描述】:
我通过迭代大量对象来生成 Vue 组件的内容。我想使用计算属性来确定是否显示某些节点,但由于计算引用在循环内使用,我需要能够动态设置引用名称。
下面是我正在尝试做的一个概念性示例。如何根据当前项目更改showItemX?
<template>
<ul>
<li v-for="item in myArr" v-if="showItemX">
{{ item.name }}
</li>
</ul>
</template>
<script>
export default {
data() {
return {
myArr: [{
id: 'item1',
name: 'Item 1'
}, {
id: 'item2',
name: 'Item 2'
}]
};
},
computed: {
showItem1: function() {
return this.$store.state.showItem1;
},
showItem2: function() {
return this.$store.state.showItem2;
}
}
}
</script>
2 种可能的解决方案
到目前为止,这是我考虑过的两条路线,但我不确定哪一条更有效,或者是否更喜欢另一种方式:
1。返回计算属性的单个对象
在此选项中,上面的两个计算属性将合并为一个属性:
computed: {
showItem: function() {
return {
item1: this.$store.state.showItem1,
item2: this.$store.state.showItem2
}
}
}
那么v-if 将被设置为showItem[item.id]:
<li v-for="item in myArr" v-if="showItem[item.id]">
{{ item.name }}
</li>
这里的缺点是,每次依赖项之一发生变化时,似乎整个对象都会重新计算。
2。使用方法获取对应的计算属性
这里我尝试将item.id 传递给一个方法,作为访问相应计算属性的一种方式:
computed: {
item1Show: function() {
return this.$store.state.showItem1;
},
item2Show: function() {
return this.$store.state.showItem2;
}
},
methods: {
showItem: function(id) {
return this[id + 'Show']
}
}
在模板中:
<li v-for="item in myArr" v-if="showItem(item.id)">
{{ item.name }}
</li>
同样,在此示例中,我不确定我是否充分利用了计算属性。
是否应该优先选择这些选项中的一个,或者是否有更好的方法来完成我所缺少的?
【问题讨论】:
-
我不知道这是否适用于你的情况,但也许stackoverflow.com/a/49032149/392102
-
@RoyJ 这让我想到了一个我没有考虑过的可能性。我想我可以使用单个计算属性为每个单独的项目创建一个子组件,该属性根据当前项目的 id 提供正确的逻辑。
标签: vue.js vuejs2 vue-component computed-properties