vue input进行v-model双向绑定后,在watch中监听绑定的值,当在watch中设置value值时,input内容未实时改变。

例如:

<input type="text" v-model="value" />

watch中监听并设置value的最大长度为50,这样的写法会不生效。此时input的输入长度并没有立刻被限制,还可以继续输入。

watch: {
  value(newVal, oldVal) {
    if (newVal.length > 50) {
      newVal = newVal.slice(0, 50)
      this.value = newVal
    }
  }
}

正确写法:

watch: {
  value(newVal, oldVal) {
    if (newVal.length > 50) {
      newVal = newVal.slice(0, 50)
      this.$nextTick(() => {
        this.value = newVal
      })
    }
  },
}

你可能感兴趣的:(vue)