Satnam Singh
Satnam Singh

Reputation: 334

DOM not updating in vue.js even when data changes

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.

Upvotes: 1

Views: 2784

Answers (2)

Shoejep
Shoejep

Reputation: 4849

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>

Upvotes: 1

Steven B.
Steven B.

Reputation: 9372

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

data () {
  return {
    error: '',
    model: model,
  };
}

Upvotes: 1

Related Questions