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

Time:04-16

v-if="!item.checked" is causing a problem. item.checked not defined. Property "item" was accessed during render but is not defined on instance.

Following the reference, this looks valid to me:

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

Reference: 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>

CodePudding user response:

From your link it says:

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):

Example follows:

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