为什么vue单项数据绑定,子组件只能响应一次父组件的值变化?单项数据绑定不是数据流向页面,子组件响应父组件吗?为什么换成v-model又可以了呢?v-model我记得是双向绑定,父子组件可以相互影响
子组件代码:
<template>
<el-dialog :model-value="visible"
@close="emit('update:visible',false)" />
</template>
<script setup lang="ts">
import { watch } from 'vue';
const props = defineProps({
visible: {
type: Boolean,
required: true,
}})
const emit = defineEmits(['update:visible']);
watch(() => props.visible, (newVal) => {
console.log('visible changed to:', newVal);
});
</script>
父组件代码
<template>
<el-button type="primary" @click="testVisible=true" >
编辑
</el-button>
<TestDialog :visible="testVisible" />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import TestDialog from '../components/TestDialog.vue';
const testVisible=ref(false)
</script>
问ai,ai说:"在 Vue 中,v-bind 绑定到子组件的 props 上,是响应式的。也就是说,如果父组件中的绑定值发生变化,子组件接收到的 props 值也会随之更新。"
这就让我更想不通了,不明白,而且为什么只能响应一次?这里面是有什么特殊原因吗?为什么v-model又可以了呢?如果说是子组件无法影响父组件我能理解,但是现在是父组件无法影响子组件啊
搞明白原因了,因为emit只会自动更新v-model的值,v-bind虽然依然会触发事件,但是不会自动更新,所以父组件的值一直是true,改成testVisible=!testVisible试了下,发现子组件可以响应。v-model实际上等价于v-bind @update:modelValue