Javascript Vue.js watcher复制提供空引用的输入
我正在尝试在Vue.js中建立一个监视程序,以便有条件地复制输入。使用value属性,我不断遇到空引用,有人会详细解释为什么会出现这种情况,以便我更好地理解这个问题吗 我的HTML:Javascript Vue.js watcher复制提供空引用的输入,javascript,vue.js,dom,Javascript,Vue.js,Dom,我正在尝试在Vue.js中建立一个监视程序,以便有条件地复制输入。使用value属性,我不断遇到空引用,有人会详细解释为什么会出现这种情况,以便我更好地理解这个问题吗 我的HTML: 名称 称呼 我的Vue代码: new Vue({ el: '#company-form', data: { legalName: null, communicationsName: null, }, watch: { legalNa
名称
称呼
我的Vue代码:
new Vue({
el: '#company-form',
data: {
legalName: null,
communicationsName: null,
},
watch: {
legalName: function() {
if (!this.communicationsName.value || this.legalName.value == this.communicationsName.value) {
this.communicationsName.value = this.legalName.value;
}
}
},
});
控制台错误:
[Vue warn]: Error in callback for watcher "legalName": "TypeError: Cannot read property 'value' of null"
vue.js:18 TypeError: Cannot read property 'value' of null
改用计算属性
您可以根据您的用例调整此代码。该指令用于创建双向数据绑定
不要做this.communicationsName.value
只需做this.communicationsName
数据属性communicationsName
已经包含您要查找的值,它不是HTMLInputElement
实例,因此它具有值
属性
请尝试以下操作:
watch: {
legalName: function() {
//Check to see if communicationsName's value is null or equal to legalName's value before duplicating input field text
if (!this.communicationsName || this.legalName == this.communicationsName) {
this.communicationsName = this.legalName;
}
}
},
注意:
if
条件this.legalName==this.communicationsName
可能不是必需的。数据属性已经具有相同的值。您可以显示一条警告,让用户知道这些值不同,并让他们决定这是正确的还是可以修复。我将更新答案,不要在条件中使用==null
,如果
条件,我们将检查错误值。如果您键入一个输入,然后删除所有内容,则该值将是一个空字符串,条件将失败。
watch: {
legalName: function() {
//Check to see if communicationsName's value is null or equal to legalName's value before duplicating input field text
if (!this.communicationsName || this.legalName == this.communicationsName) {
this.communicationsName = this.legalName;
}
}
},