Vue.js观察者复制输入给出空引用

问题描述 投票:1回答:2

我试图在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
javascript vue.js dom
2个回答
0
投票

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可能没有必要。数据属性已具有相同的值。


0
投票

请改用Computed Properties

new Vue({
    el: '#company-form',
    data: {
        communicationsName: null,
    },
    computed: {
        legalName() {
           return this.communicationsName
         }
     },
});

您可以根据您的使用案例调整此代码。

© www.soinside.com 2019 - 2024. All rights reserved.