问题描述
在子组件调用父组件的方法实现勾选的功能时,只是实现了子组件的页面更新,而父组件不更新,而加了
this.$forceUpdate()就能更新了,为什么不加就不生效呢?
修改了父组件的data后,进而影响了子组件的模板更新
export default {
name: "App",
components: {
MyFooter,
MyHeader,
MyList,
},
// 数据在哪里对数据的操作就在哪里
data() {
return {
todos: [
{ id: "001", title: "吃饭", done: true },
{ id: "002", title: "睡觉", done: false },
{ id: "003", title: "学习", done: true },
],
};
},
methods: {
// 勾选or取消勾选一个todo
handleCheck(id) {
this.todos.forEach((todo) => {
if (id === todo.id) {
todo.done = !todo.done;
//this.$forceUpdate()
}
});
},
},
};
通过change事件点击,done不变化
this.$forceUpdate()
<template>
<div id="app">
<MyList :todos="todos" @handleCheck="handleCheck"></MyList>
<div v-for="item in todos" :key="item.id" @click="handleCheck(item.id)">
父组件---{{ item.title }}{{item.done}}
</div>
</div>
</template>
<script>
import MyList from "./components/MyList.vue";
export default {
name: "App",
components: {
MyList,
},
// 数据在哪里对数据的操作就在哪里
data() {
return {
todos: [
{ id: "001", title: "吃饭", done: true },
{ id: "002", title: "睡觉", done: false },
{ id: "003", title: "学习", done: true },
],
};
},
methods: {
// 勾选or取消勾选一个todo
handleCheck(id) {
console.log(id);
this.todos.forEach((todo) => {
if (id === todo.id) {
todo.done = !todo.done;
// this.$forceUpdate();
}
});
console.log(this.todos);
},
},
updated() {
console.log("父组件更新");
},
watch: {
todos: {
deep: true,
handler() {
console.log("监视")
},
},
},
};
</script>
<style>
</style>
<template>
<div>
<div v-for="item in todos" :key="item.id" @click="btn(item.id)">
{{ item.title }}{{item.done}}
</div>
</div>
</template>
<script>
export default {
name: "MyList",
props: {
todos: Array,
},
methods: {
btn(id){
this.$emit("handleCheck",id)
}
},
updated(){
console.log("子组件更新");
}
};
</script>
<style scoped>
</style>
你说的data改了,子组件更新了,但是父组件没有更新,是因为父组件的模板里面没有用到todos数据,因此todos发现修改,父组件是不会更新的,数据驱动视图,视图没有用到这个数据,这个数据改变是无法驱动视图的。你像我一样在父组件中用一下todos数据,你就会发现父组件会触发更新了。
望采纳!