昨天在做项目时遇到了一个问题 在Vue中监听obj.name时新增了一个属性 但是发现属性并没有变化 后来查询了官方文档发现Vue不允许动态添加prototype来执行深度监听
# 对象
如下:
<template>
<div class="about">
<h1>{{dataList.name}}</h1>
<h1>{{dataList.id}}</h1>
<h1>{{dataList.type}}</h1>
</div>
</template>
<script>
export default {
data(){
return {
dataList:{name:123,id:456},
}
},
mounted(){
setTimeout(() => {
// this.$set(this.dataList,'type','student');
this.dataList.type='student'
}, 2000);
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
两秒后页面不会发生任何变化 改动后:
<template>
<div class="about">
<h1>{{dataList.name}}</h1>
<h1>{{dataList.id}}</h1>
<h1>{{dataList.type}}</h1>
</div>
</template>
<script>
export default {
data(){
return {
dataList:{name:123,id:456},
}
},
mounted(){
setTimeout(() => {
this.$set(this.dataList,'type','student');
// this.dataList.type='student'
}, 2000);
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
出现student
# 数组
<template>
<div class="about">
<h1>{{ dataList.name }}</h1>
<h1>{{ dataList.id }}</h1>
<h1>{{ dataList.type }}</h1>
<div v-for="(item,idex) in dataArr" :key="idex">{{item}}</div>
</div>
</template>
<script>
export default {
data() {
return {
dataList: { name: 123, id: 456 },
dataArr: ["1", "2", "3"],
};
},
mounted() {
setTimeout(() => {
// this.$set(this.dataList,'type','student');
// this.dataList.type='student'
this.dataArr[0] = "4";
}, 2000);
},
};
</script>
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
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
两秒后。。。什么都没有发生
<template>
<div class="about">
<h1>{{ dataList.name }}</h1>
<h1>{{ dataList.id }}</h1>
<h1>{{ dataList.type }}</h1>
<div v-for="(item,idex) in dataArr" :key="idex">{{item}}</div>
</div>
</template>
<script>
export default {
data() {
return {
dataList: { name: 123, id: 456 },
dataArr: ["1", "2", "3"],
};
},
mounted() {
setTimeout(() => {
// this.$set(this.dataList,'type','student');
// this.dataList.type='student'
// this.dataArr[0] = "4";
this.dataArr.splice(0, 1, '4')
}, 2000);
},
};
</script>
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
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
成功刷新