vue v-model失效原因及解决方案

  1. 绑定的值没有及时更新,可能是由于异步操作导致的。
<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>

解决方案:
可以使用 Promise 或 async/await 等方式来等待异步操作完成后再更新数据,或者使用 Vue.nextTick 方法来确保 DOM 已经更新。

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. 绑定的值在组件内部被修改,但是没有使用 Vue.set 或 this.$set 方法来更新,导致变化无法被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>

解决方案:当需要修改一个数组或对象中的某个元素时,应该使用 Vue.set 或 this.$set 方法来更新

this.$set(this.list, this.list.length, newItem) 
  1. 其值是只读属性

猜你喜欢

转载自blog.csdn.net/weixin_43989656/article/details/129692029