Vue.js v-for 和 v-if 没有像参考示例中那样一起工作

Vue.js v-for & v-if not working together as in reference example

v-if="!item.checked" 导致了问题。 item.checked 未定义。 属性“项目”在渲染期间被访问但未在实例上定义。

按照参考,这对我来说有效:

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

参考:https://vuejs.org/guide/essentials/list.html#v-for-with-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>

你的 link 说:

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

This can be fixed by moving v-for to a wrapping tag (which is also more explicit):

示例如下:

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