英文:
How to use v-if inside v-for loop in vue.js 2
问题
<div v-for="person in persons">
<div v-if="person.status == 'public'" :key="person.id">
Hi, my name is {{person.name}}
</div>
<div v-else :key="person.id">
This person is private
</div>
</div>
所有person
对象中status
属性的值都是'public',全部都是!
但在上面的代码片段中,执行的不是if
块,而是一直执行else
块。
如果我将代码重写如下:
<div v-for="person in persons" :key="person.id">
<div v-if="person.status == 'public'">
Hi, my name is {{person.name}}
</div>
<div v-else>
This person is private
</div>
</div>
那么它将正常工作。
第一个代码片段有什么问题?
看起来是key
属性在其中起了作用。我是否使用它不正确?为什么它会影响输出?
哪种方法是在for
循环中编写if
语句的最正确方式?
我之前在我的代码中的其他循环中一直在使用第一种方法,没有问题,直到今天。我是否需要更新它们都像第二种方法那样,以避免出现这样的奇怪行为?
英文:
I have this code setup
<div v-for="person in persons">
<div v-if="person.status == 'public'" :key="person.id">
Hi,my name is {{person.name}}
</div>
<div v-else :key="person.id">
This person is private
</div>
</div>
All the values of the status
property in the person
`s object are 'public', all!
But in the code snipet above, instead of the if
block to run, it is the else
block that keeps running.
If I re-write the code like this:
<div v-for="person in persons" :key="person.id">
<div v-if="person.status == 'public'">
Hi,my name is {{person.name}}
</div>
<div v-else>
This person is private
</div>
</div>
then it works correctly.
What is wrong with the first snippet?
It looks like the 'key' attribute has a hand in this. Am I using it incorrectly? Why is it affecting the output?
Which of them is the most correct way of writing 'if' statement inside 'for' loop?
I have been using the first method previously in other loops in my code, no issues until today. Do I need to update all of them to look like the second method to avoid strange behaviours like this?
答案1
得分: 0
从Vue的v-for with v-if页面:
> 当它们存在于同一个节点上时,v-if的优先级高于v-for。这意味着v-if条件将无法访问v-for范围内的变量。
你正在正确使用v-for
与v-if
。问题出在将:key
放在条件块上。
无论如何,div中都会渲染出一些内容,你有两种可能的结果,key
应该在具有v-for
的行上。不应该有条件地渲染:key
属性。
// 1
<div>
<div>
你好,我的名字是约翰
</div>
</div>
// 2
<div>
<div>
这个人是私人的
</div>
</div>
英文:
From vue v-for with v-if
> When they exist on the same node, v-if has a higher priority than v-for. That means the v-if condition will not have access to variables from the scope of the v-for
You are using the v-for
with v-if
correctly. The problem is with :key
being put on the conditional blocks.
Either way, something will render in the div, you have two possible outcomes and the key should be on the line with the v-for
. You should not conditionally render :key
attribute.
// 1
<div>
<div>
Hi,my name is john
</div>
</div>
// 2
<div>
<div>
This person is private
</div>
</div>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论