Vue v-model failure reasons and solutions

  1. The bound value was not updated in time, possibly due to an asynchronous operation.
<template>
  <div>
    <input v-model="name" />
    <button @click="updateName">Update Name</button>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      name: 'John',
    }
  },
  methods: {
    
    
    updateName() {
    
    
      setTimeout(() => {
    
    
        this.name = 'Jane' // 异步更新 name 值
      }, 1000)
    },
  },
}
</script>

Solution:
You can use Promise or async/await to wait for the asynchronous operation to complete before updating the data, or use the Vue.nextTick method to ensure that the DOM has been updated.

updateName() {
    
    
  // 使用 Promise
  setTimeout(() => {
    
    
    this.name = 'Jane' // 异步更新 name 值
  }, 1000).then(() => {
    
    
    this.$nextTick(() => {
    
    
      console.log(this.$el.querySelector('input').value) // 输出 'Jane'
    })
  })

  // 使用 async/await
  setTimeout(async () => {
    
    
    this.name = 'Jane' // 异步更新 name 值
    await this.$nextTick()
    console.log(this.$el.querySelector('input').value) // 输出 'Jane'
  }, 1000)
},

  1. The bound value is modified inside the component, but it is not updated using the Vue.set or this.$set method, resulting in changes that cannot be monitored by Vue.
<template>
  <div>
    <div v-for="(item, index) in list" :key="index">
      <input v-model="item.name" />
    </div>
    <button @click="addNewItem">Add New Item</button>
  </div>
</template>

<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      list: [
        {
    
     name: 'John' },
        {
    
     name: 'Jane' },
      ],
    }
  },
  methods: {
    
    
    addNewItem() {
    
    
      const newItem = {
    
     name: 'New Item' }
      this.list.push(newItem) // 修改 list 数组,但是没有使用 Vue.set 或 this.$set 方法
      // this.$set(this.list, this.list.length, newItem) // 使用 this.$set 方法更新数组,使其能够被 Vue 监测到
    },
  },
}
</script>

Solution: When you need to modify an element in an array or object, you should use the Vue.set or this.$set method to update

this.$set(this.list, this.list.length, newItem) 
  1. Its value is a read-only property

Guess you like

Origin blog.csdn.net/weixin_43989656/article/details/129692029