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!
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);
It is tricky, but you could iterate over the data properties and:
data
properties;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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With