<p id="app">
<h1>
{{ count.id }}
</h1>
<h2>
{{ item[0].id }}
</h2>
</p>
<script>
let vm = new Vue({
el: '#app',
data () {
return {
item: [
{
id: 60
}
],
count: {}
}
},
mounted () {
this.count = this.item[0]; // 赋值给count
}
});
</script>
Print in the console: vm.count.id--
You will find that items.id has also been changed. I obviously only changed count.id
How to avoid synchronization? I just want to change count.id;
The problem of shallow copy and deep copy.
This is still a basic issue with JS data types.
Judging from the code you provided, item is an array. Assigning an array to another variable only assigns a reference. Both of them refer to an array. Of course, if you change this array, all references to this array will change.
Solution 1:
An array is an index structure, which means it is equivalent to two pointers pointing to the same place, so if you change one of them, the other will also change. As for how to avoid it, I recommend using destructuring assignment in ES6. You can refer to the documentation.
Give me an example: