熟悉 Vue ?你能解释这个死循环吗?

最新填坑:Vue 源码(一):响应式原理

====== 更新线 =====
评论区有了相关讨论,贴更详细一点的解释出来

====== 更新线 =====
循环出现的条件:

  • key="Math.random()"
  • 子组件在 created 中输出计算属性并改变 data

与 Vue watcher 的添加机制有关,初步认为是 Vue 的小 bug,dep 对象的 targetStack 管理不当导致

================== 分割线 ===============

把下面的代码拷到你的 html 文件,在浏览器打开你会看到控制台报了死循环的错,知道为什么吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<body>
<div id="app">
<child-comp v-for="i in [1]" :key="Math.random()" :sub-prop="parentData"></child-comp>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
Vue.component('child-comp', {
props: {
subProp: {}
},
data() {
return {
subData: []
};
},
template: '<div></div>',
computed: {
subComputed() {
return '222';
}
},
created() {
console.log(this.subComputed);
this.subData.push(1);
}
});
vm = new Vue({
el: '#app',
data() {
return {
parentData: 'hello world'
};
}
})
</script>
</body>