Vue.js v-for 和 v-if 不协同工作,如参考示例所示



v-if="!项目。已检查";正在引发问题。项检查未定义。属性";项目";在渲染期间访问了,但未在实例上定义。

根据参考,这对我来说是有效的:

<li v-for="item in items" v-if="!item.checked">

参考:https://vuejs.org/guide/essentials/list.html#v-用于带-v-if

<html>
<head>
<script src="https://unpkg.com/vue@3"></script>
</head>
<body>
<div id="app">
<ol v-if="hasItems">
<li v-for="item in items" v-if="!item.checked" :key="item.id">
<input type="checkbox" v-model="item.checked">
<label :style="{ textDecoration: item.checked ? 'line-through' : 'none' }">
{{ item.name }}
{{ item.checked }}
</label>
</li>
</ol>
<p v-else>List is empty</p>
<!-- v-else-if="" -->
<!-- v-else -->
<form @submit.prevent="addItem">
Add item:
<input type="text" v-model="newItem">
</form>
<p v-show="hasItems">
{{ totalAmountMessage }}
</p>
</div>
<script>
Vue.createApp({
data() {
return {
newItem: '',
items: [],
}
},
computed: {
totalAmountMessage() {
if (this.totalAmountOfItems === 1) {
return `${this.totalAmountOfItems} item in our list`
}
return `${this.totalAmountOfItems} items in our list`
},
hasItems() {
return this.totalAmountOfItems !== 0
},
totalAmountOfItems() {
return this.items.length
},
},
methods: {
addItem() {
this.items.push({
id: Math.random(),
name: this.newItem,
checked: false
})
this.newItem = ''
}
}
}).mount('#app')
</script>
</body>
</html>

从您的链接中显示:

当它们存在于同一节点上时,v-if的优先级高于v-for。这意味着v-if条件将无法访问v-for范围内的变量

这可以通过将v-for移动到包装标签(也更明确)来修复:

示例如下:

<template v-for="todo in todos">
<li v-if="!todo.isComplete">
{{ todo.name }}
</li>
</template>

最新更新