javascript - vue responsiveness problem
滿天的星座
滿天的星座 2017-05-19 10:39:39
0
3
545
<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;

滿天的星座
滿天的星座

reply all(3)
phpcn_u1582

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:

this.count = this.item.slice(0, 1);
Peter_Zhu

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:

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template