我试图在Vue.js中建立一个观察者来有条件地复制输入。使用value属性,我一直在体验空引用,有人会详细解释为什么这可能是这样我可能更好地理解这个问题?
我的HTML:
<div id="company-form">
<label>Name</label>
<input v-model="legalName" type="text"/>
<label>Name To Call</label>
<input v-model="communicationsName" />
</div>
我的观看代码:
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
v-model
指令用于创建双向数据绑定。
而不是做this.communicationsName.value
只做this.communicationsName
。
数据属性communicationsName
已经拥有您正在寻找的值,它不具有HTMLInputElement
实例,因为它具有value
属性。
请尝试以下方法:
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
可能没有必要。数据属性已具有相同的值。
请改用
Computed Properties
。
new Vue({
el: '#company-form',
data: {
communicationsName: null,
},
computed: {
legalName() {
return this.communicationsName
}
},
});
您可以根据您的使用案例调整此代码。