官网:
实现
父组件:
<template>
<ChangePwdDialog v-model:visible='is_visible'/>
<template>
<script setup>
import ChangePwdDialog from "./changePwdDialog.vue";
const is_visible = ref(false);
</script>
子组件(changePwdDialog.vue
):
<template>
<el-dialog :before-close="close" v-model="visible" title="修改密码">
<template #footer>
<span>
<el-button @click="close">取消</el-button>
<el-button type="primary" @click="close">确认</el-button>
</span>
</template>
</el-dialog>
</template>
<script setup>
import { ref, watch} from "vue";
const props = defineProps({
visible: Boolean,
});
const v = ref(props.visible);
watch(
() => props.visible,
(value) => {
console.log(value);
v.value = value;
}
);
const emit = defineEmits(["update:visible"]);
// 关闭弹窗
const close = () => {
v.value = false;
emit("update:visible", v.value);
};
</script>
说明
属性v
并没有直接控制dialog,相反,dialog通过v-model绑定的值一直是visible
原因:
visible
是父组件给子组件传的值,子组件不能直接修改,而应该取出visible
的值赋值给一个响应式ref
也就是v
实现步骤:
- 监听
visible
的值及时赋值给v.value
,来形成visible更新->v更新的同步 - 创建一个
emit
,名字要叫update:父组件给子组件传的props名
- 创建控制
v
的函数(close),并通过调用emit
对父组件的visible
进行更新,形成v更新->visible更新的同步 - el-dialog 要加:before-close=“close”,不然点击空白处或关闭按钮不能修改
visible