1

I'm attempting to establish a watcher in Vue.js to duplicate an input conditionally. Using the value property, I keep experiencing null references, will someone elaborate to why this may be so I may better understand the issue?

My HTML:

<div id="company-form">
    <label>Name</label>
    <input v-model="legalName" type="text"/>
    <label>Name To Call</label>
    <input v-model="communicationsName" />                      
</div>

My Vue code:

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;                       
            }
         }
     },
});

Console Errors:

[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
0

2 Answers 2

1

The v-model directive is used to create two-way data bindings.

Instead of doing this.communicationsName.value just do this.communicationsName.

The data property communicationsName already holds the value you are looking for, it is not an HTMLInputElement instance for it to have a value property.

Try the following:

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;                       
        }
     }
 },

Note: The if condition this.legalName == this.communicationsName might not be necessary. The data properties already have the same value.

Sign up to request clarification or add additional context in comments.

1 Comment

You could show a warning to let the user know the values are different and let them decide if that is okay or they fix it. I will update the answer, do not use == null in the if condition, we'll check for a falsy value instead. If you type into an input and then erase everything, the value will be an empty string and the condition will fail.
1

Use Computed Properties instead.

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

You can tweak this code as per your use case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.