search

Home  >  Q&A  >  body text

javascript - vue responsiveness problem

<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;

滿天的星座滿天的星座2816 days ago573

reply all(3)I'll reply

  • phpcn_u1582

    phpcn_u15822017-05-19 10:41:39

    The problem of shallow copy and deep copy.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:41:39

    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);

    reply
    0
  • 天蓬老师

    天蓬老师2017-05-19 10:41:39

    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:

    reply
    0
  • Cancelreply