我可以在嵌套在 'method' 中的 'v-for' 中使用 'index' 参数吗?
Can I use the 'index' argument in 'v-for' nested in a 'method'?
我需要在 v-for
上使用索引,但在与 directive
本身相同的级别上,以便 mutate
显示的状态。
<template>
<div>
<div v-for="share in sharesPurchased()" :key="share">
<div>
<h4>This is some content</h4>
<p style="border: solid 1px">{{share.count}}</p>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
shares: [
{id: 'BMW', count: 1},
{id: 'Ford', count: 0},
{id:'Apple', count: 10}
]
}
},
methods: {
sharesPurchased() {
// I want to use this at the v-for level to limit content view
}
}
}
</script>
我想限制在此迭代中显示的内容,因此我只显示带有 count > 0
的内容,即:shares[i].count > 0
我按照上述意图的结果应该 <p style="border: solid 1px">{{share.count}}</p>
只显示 1
因为只有 this.shares[0].count
是 >
然后 0
更新:根据您的使用需要,这显然是一个X-Y问题。您应该改用计算属性:
computed: {
filteredSharesByCount: function() {
return this.shares.filter(share => share.count > 0);
}
}
然后您可以在模板中引用它:
过时的答案:
v-for
绑定中的index is accessible as the second optional argument:
v-for
also supports an optional second argument for the index of the current item.
即:
<div v-for="(share, idx) in sharesPurchased(shares)" :key="share">
然后,如果您希望某个方法可以访问索引,则可以在循环中简单地使用 idx
。
我需要在 v-for
上使用索引,但在与 directive
本身相同的级别上,以便 mutate
显示的状态。
<template>
<div>
<div v-for="share in sharesPurchased()" :key="share">
<div>
<h4>This is some content</h4>
<p style="border: solid 1px">{{share.count}}</p>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
shares: [
{id: 'BMW', count: 1},
{id: 'Ford', count: 0},
{id:'Apple', count: 10}
]
}
},
methods: {
sharesPurchased() {
// I want to use this at the v-for level to limit content view
}
}
}
</script>
我想限制在此迭代中显示的内容,因此我只显示带有 count > 0
的内容,即:shares[i].count > 0
我按照上述意图的结果应该 <p style="border: solid 1px">{{share.count}}</p>
只显示 1
因为只有 this.shares[0].count
是 >
然后 0
更新:根据您的使用需要,这显然是一个X-Y问题。您应该改用计算属性:
computed: {
filteredSharesByCount: function() {
return this.shares.filter(share => share.count > 0);
}
}
然后您可以在模板中引用它:
过时的答案:
v-for
绑定中的index is accessible as the second optional argument:
v-for
also supports an optional second argument for the index of the current item.
即:
<div v-for="(share, idx) in sharesPurchased(shares)" :key="share">
然后,如果您希望某个方法可以访问索引,则可以在循环中简单地使用 idx
。