英文:
How do I chain multiple conditions in a Vue JS v-if conditonal?
问题
<div class="person" v-for="user in users" v-if="user.country === '美国' || user.country === '日本'">
<span>{{ user.first_name }}, {{ user.last_name }}</span>
<a :href="'mailto:' + user.email.toLowerCase()">{{ user.email }}</a>
<span>{{ user.country }}</span>
</div>
英文:
I am trying to only show results that match several countries. I must have the syntax wrong and I have tried various different ways. Any help would be greatly appreciated.
<div class="person" v-for='user in users' v-if="user.country === 'United States || user.country === Japan'">
<span>{{ user.first_name }}, {{ user.last_name }}</span>
<a :href="'mailto:' + user.email | lowercase">{{ user.email }}</a>
<span>{{ user.country }}</span>
</div>
```
</details>
# 答案1
**得分**: 1
你有一个错误 - 未闭合的引号,修复方法是:
```html
v-if="user.country === 'United States' || user.country === 'Japan'"
但是Vue3文档说:
不建议在同一元素上同时使用v-if和v-for,因为存在隐式优先级。请参考样式指南获取详细信息。
所以你可能应该这样做:
<template v-for="user in users">
<div class="person" v-if="user.country === 'United States' || user.country === 'Japan'">
<span>{{ user.first_name }}, {{ user.last_name }}</span>
<a :href="'mailto:' + user.email | lowercase">{{ user.email }}</a>
<span>{{ user.country }}</span>
</div>
</template>
但是我的首选方式是使用计算属性:
<script setup>
// ...
const filteredUsers = computed(() => users.filter(user => ['United States', 'Japan'].includes(user.country)));
// ...
</script>
<template>
<div class="person" v-for="user in filteredUsers">
<span>{{ user.first_name }}, {{ user.last_name }}</span>
<a :href="'mailto:' + user.email | lowercase">{{ user.email }}</a>
<span>{{ user.country }}</span>
</div>
</template>
英文:
You have an error - an unclosed quote, the fix is:
v-if="user.country === 'United States' || user.country === 'Japan'"
But the Vue3 docs say:
> It's not recommended to use v-if and v-for on the same element due to implicit precedence. Refer to style guide for details.
so you should probably do:
<template v-for="user in users">
<div class="person" v-if="user.country === 'United States' || user.country === 'Japan'">
<span>{{ user.first_name }}, {{ user.last_name }}</span>
<a :href="'mailto:' + user.email | lowercase">{{ user.email }}</a>
<span>{{ user.country }}</span>
</div>
</template>
But my preferred way is to use a computed:
<script setup>
...
const filteredUsers = computed(() => users.filter(user => ['United States', 'Japan'].includes(user.country)));
...
</script>
<template>
<div class="person" v-for="user in filteredUsers">
<span>{{ user.first_name }}, {{ user.last_name }}</span>
<a :href="'mailto:' + user.email | lowercase">{{ user.email }}</a>
<span>{{ user.country }}</span>
</div>
</template
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论