Vue.js观察者重复输入以提供空引用

我试图在Vue.js中建立观察者以有条件地复制输入。使用value属性,我会不断遇到null引用,有人会详细说明为什么会这样,以便我可以更好地理解该问题吗?


我的HTML:


<div id="company-form">

    <label>Name</label>

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

    <label>Name To Call</label>

    <input v-model="communicationsName" />                      

</div>

我的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


aluckdog
浏览 205回答 2
2回答

月关宝盒

该v-model指令用于创建双向数据绑定。而不是做的this.communicationsName.value就去做this.communicationsName。data属性communicationsName已经包含您要查找的值,它不是HTMLInputElement拥有value属性的实例。请尝试以下方法:watch:&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;legalName:&nbsp;function()&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Check&nbsp;to&nbsp;see&nbsp;if&nbsp;communicationsName's&nbsp;value&nbsp;is&nbsp;null&nbsp;or&nbsp;equal&nbsp;to&nbsp;legalName's&nbsp;value&nbsp;before&nbsp;duplicating&nbsp;input&nbsp;field&nbsp;text &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(!this.communicationsName&nbsp;||&nbsp;this.legalName&nbsp;==&nbsp;this.communicationsName)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.communicationsName&nbsp;=&nbsp;this.legalName;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;},注意:该if条件this.legalName == this.communicationsName可能不是必需的。数据属性已经具有相同的值。

交互式爱情

使用Computed Properties代替。new Vue({&nbsp; &nbsp; el: '#company-form',&nbsp; &nbsp; data: {&nbsp; &nbsp; &nbsp; &nbsp; communicationsName: null,&nbsp; &nbsp; },&nbsp; &nbsp; computed: {&nbsp; &nbsp; &nbsp; &nbsp; legalName() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return this.communicationsName&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;},});您可以根据用例调整此代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript