1

The changes are not reflected in DOM, even when the data is changing properly. Here is a very basic example to demonstrate the issue -

<template>
  <input type="text" v-model="username" />
  <p>{{error}}</p>
  <button @click="saveData">Save</button>
</template>

<script>
  export default {
    data () {
      model.error = ''; // adding a new property
      return model; // 'model' is a global variable
    }
    methods: {
      saveData() {
        if (!this.username) {
          this.error = 'Please enter the username!';
          return;
        }
        // ... other code
      }
    }
  };
</script>

After calling saveData() the error variable contains the message if username is not filled. But it's not showing up in the paragraph.

There is a trick. If I also change the username property when the error variable is changed, the changes are reflected.

2
  • The object returned from data is used directly to create the $data for the component. If you use the same model object in multiple components they will all end up sharing the same $data object. That includes the error property. Is that really what you want? If it is then just add an error property to the initial definition of model so that the property is made reactive when Vue first encounters that object. Commented May 13, 2020 at 14:48
  • I want to add error property only to this component. Can you show me how to do that? Commented May 13, 2020 at 14:53

2 Answers 2

1

You need to return error or Vue doesn't have access to it.

data () {
  return {
    error: '',
    model: model,
  };
}
Sign up to request clarification or add additional context in comments.

2 Comments

I will have to add model keyword while accessing each property. I tried adding error variable in model & then returning the model, but still didn't work.
I updated the question... and it still doesn't work
1

You should be able to achieve what you're trying to do, as long as error and username properties are defined on model for data. I've included a simple snippet below, showing it working. Take a look at Declaring Reactive Properties in the documentation.

var model = {
  username: "Default"
};


new Vue({
  el: "#app",
  data: () => {
    model.error = model.error || "";
    return model;
  },
  methods: {
    updateError() {
      this.error = "Test";
    },
    updateUsername() {
      this.username = "Hello, World!";
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button type="button" @click="updateError">Update Error</button>
  <button type="button" @click="updateUsername">Update Username</button>
  <div>Error: {{error}}</div>
  <div>UserName: {{username}}</div>
</div>

1 Comment

I found that problem is with model object. If I try any other object, it works!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.