【问题标题】:Vue v-model issue when using a computed setter使用计算设置器时的 Vue v-model 问题
【发布时间】:2021-07-16 02:22:31
【问题描述】:

我想创建一个用户可以填写的输入字段。问题是我不希望他们用特殊字符填写这个字段。目前,我有这个 html 设置:

    <input class="rc-input-editing" id="bioInput" type="text" v-model="wrappedBioName">

还有这个 Vue.js 设置(如您所见,我正在尝试使用计算的 setter 来解决这个问题):

    data () {
      return {
        newBioName: '',
      }
    },
    computed: {
      wrappedBioName: {
        get () {
          alert('getting new name!')
          return this.newBioName
        },
        set: function (newValue) {
          const restrictedChars = new RegExp('[.*\\W.*]')
          if (!restrictedChars.test(newValue)) {
            this.newBioName = newValue
          }
        }
      }

目前,我的问题是客户端能够继续填写文本输入字段,即使 this.newBioName 没有更新。换句话说,他们可以在输入字段中输入特殊字符,即使 this.newBioName 没有被这些特殊字符更新。

鉴于我目前对 v-model 的理解,这种行为与我的预期不同。根据我到目前为止所阅读的内容,v-model 将输入元素绑定到一些 vue 实例数据,并将 vue 实例数据绑定到输入元素(双向绑定)。因此,我期望文本输入字段中的文本将直接匹配 this.newBioName 的值。

很明显,我错过了一些东西,希望能有第二双眼睛!

【问题讨论】:

标签: vue.js input v-model


【解决方案1】:

Vue.js 双向绑定系统无法按预期工作。每个绑定过程每次都以一种方式工作。所以,你应该做的就是不要让输入文本发生变化。

尝试 keypress 事件而不是这样的计算属性:

<input class="rc-input-editing" id="bioInput" type="text" v-model="newBioName" @keypress="nameKeyPressAction">
data() {
    return {
        newBioName: ""
    };
},
methods: {
    nameKeyPressAction(event) {
        const restrictedChars = new RegExp("[.*\\W.*]");
        const newValue = this.newBioName + event.key;
        if (!restrictedChars.test(newValue))
            this.newBioName = newValue;
        return event.preventDefault();
    }
}

编辑:

当您将数据属性或计算属性设置为输入的 v-model 时,vue 会将它们关联起来,但是,如果用户通过输入更新 dom 对象,则会触发属性的 setter,并且过程到此结束。另一方面,当你在 javascript 端更改属性的值时,vue 会更新 dom 对象,这个过程也到此结束。

在您的示例代码中,您似乎希望计算属性的 getter 再次设置 dom,但它不能。该属性已通过 dom 更改更新,它也不能更新它。否则可能会出现死循环。

【讨论】:

  • 感谢您抽出额外的时间来解释双向绑定,现在它很有意义。此外,此解决方案效果很好!
猜你喜欢
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 2018-11-02
  • 2021-07-19
  • 2019-08-26
相关资源
最近更新 更多