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

文章讨论了在Vue中遇到的两个常见问题:1)由于异步操作,绑定的值没有及时更新;2)直接修改数组导致Vue无法检测变化。解决方案包括使用Promise、async/await配合$nextTick更新数据,以及使用Vue.set或this.$set方法确保数组元素变化可追踪。
摘要由CSDN通过智能技术生成
  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. 其值是只读属性
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值