Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the whole data of a vue object?

Tags:

vue.js

Simply, I just want to change the entire data of a Vue object, like this:

vueobj.$data = newdata; 

but the official document says it's not allowed:

VM156 vue.js:597 [Vue warn]: Avoid replacing instance root $data. Use nested data properties instead.

(found in )

So I tried another way: first destroy the the vueobj by $destroy(), then create a new vueobj to bind new data object to the same the UI element, but after that, the UI element still uses the old data. So how could I solve this problem? thanks!

like image 621
Jinmin Avatar asked Dec 05 '22 12:12

Jinmin


2 Answers

this works for me:

<div id="app">
  {{name}}: {{age}}
</div>

const app = new Vue({
  el: "#app",
  data: {
    name: "Alice",
    age: 30
  },
  methods: {
    refresh(data) {
      Object.assign(this.$data, data); // <--
    }
  }
});

const newData = {
  name: "Bob",
  age: 22
};

app.refresh(newData);
like image 114
tinos Avatar answered Jan 03 '23 05:01

tinos


It is tricky, but you could iterate over the data properties and:

  • First: remove all data properties;
  • Second: add each property of the newdata object to the data object.

Demo below:

new Vue({
  el: '#app',
  data: {
    name: 'Alice',
    age: 30
  },
  methods: {
    changeWholeData() {
    	 let newdata = {name: 'Bob', age: 40};
       // erase all current keys from data
       Object.keys(this.$data).forEach(key => this.$data[key] = null);
       // set all properties from newdata into data
       Object.entries(newdata).forEach(entry => Vue.set(this.$data, entry[0], entry[1]));
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>Name: {{ name }}</p>
  <p>Age: {{ age }}</p>
  <button @click="changeWholeData">Change Whole Data</button>
</div>
like image 20
acdcjunior Avatar answered Jan 03 '23 06:01

acdcjunior