父组件
<template>
<div class="home">
<button @click="addCount"> +1 </button>
<hello-world v-model:count="count"></hello-world>
</div>
</template>
<script>
import HelloWorld from "@/components/HelloWorld.vue";
import {computed, ref} from "vue";
export default {
name: "Home",
components: {
HelloWorld
},
setup(){
let count = ref(1)
const addCount = () => {
count.value++
console.log(count.value)
}
return{
count,
addCount
}
}
};
</script>
在父组件点击按钮+1,父组件的属性count会自增一,但是父组件count值改变后,理想情况子组件也会更碎父组件改变,但实际情况子组件只在首次渲染时接受父组件传入的值,在之后父组件值更新后子组件不会再接受到父组件传入的新值
子组件
<template>
<div>
<div class="point">
<span>{{countKid}}</span>
</div>
</div>
</template>
<script>
import {defineComponent, ref, watch} from "vue";
export default defineComponent({
props: {
count: {
default(){
return 0
}
}
},
setup(props, context){
let countKid = ref(props.count)
watch(countKid, (newVal, oldVal) => {
// 用于监听参数变化,但是参数指挥在首次渲染时监听到变化,之后值就没有再改变过
console.log(newVal, oldVal)
})
return {
countKid
}
}
})
</script>
老师我想在父组件的属性值count通过点击更新后,传入到子组件。子组件接受到父组件传入的属性值count后也会进行同步更新
希望实现后的效果:父组件的值改变后,会同步传递给子组件,子组件接受的值也会跟随改变
目前的情况:首次页面渲染的时候父组件传入的值子组件可以正常接收,当父组件点击按钮+1后父组件的值改变,但子组件接受的值并没有改变