suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Javascript – Vue-Reaktionsfähigkeitsproblem

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

Drucken Sie in der Konsole: vm.count.id--

Sie werden feststellen, dass auch items.id geändert wurde. Ich habe offensichtlich nur count.id geändert

Wie vermeide ich eine Synchronisierung? Ich möchte nur count.id ändern

滿天的星座滿天的星座2866 Tage vor602

Antworte allen(3)Ich werde antworten

  • phpcn_u1582

    phpcn_u15822017-05-19 10:41:39

    浅拷贝和深拷贝的问题。

    Antwort
    0
  • 淡淡烟草味

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

    这还是JS数据类型的基础问题。
    从你提供的代码判断item是个数组, 把一个数组赋值给另外一个变量,只是赋值了引用, 两个都是引用了一个数组, 当然更改这个数组,所有引用这个数组的都会发生变化。

    解决方案一:

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

    Antwort
    0
  • 天蓬老师

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

    数组是索引结构,也就是说相当于两个指针指向同一个地方,所以说你改变其中一个,另一个也会跟着改变。至于如何避免,我推荐用ES6中的解构赋值,你可以参考一下文档。
    举个栗子:

    Antwort
    0
  • StornierenAntwort