vue3父子组件弹窗
时间: 2025-05-02 14:49:00 浏览: 30
### Vue3 父子组件弹窗实现方法
#### 创建子组件 `DialogComponent.vue`
子组件负责处理弹窗的具体展示逻辑以及内部操作。
```vue
<template>
<el-dialog :visible.sync="dialogVisible" title="填写表单">
<!-- 表单项 -->
<el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules">
<el-form-item label="名称" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
<el-button type="primary" @click="handleSubmit">提交</el-button>
</el-form>
</el-dialog>
</template>
<script setup>
import { reactive, toRefs } from 'vue'
const props = defineProps({
modelValue: Boolean,
})
// 定义事件emit对象用于向父级发送消息
const emit = defineEmits(['update:modelValue', 'submit'])
let dialogVisible = computed({
get() {
return props.modelValue;
},
set(value) {
emit('update:modelValue', value);
}
});
const ruleForm = reactive({ name: '' })
const rules = {
name: [{ required: true, message: "请输入名称", trigger: "blur" }]
}
function handleSubmit() {
this.$refs.ruleFormRef.validate((valid) => {
if (valid) {
emit('submit', Object.assign({}, ruleForm))
dialogVisible.value = false; // 关闭对话框
} else {
console.log('error submit!!');
return false;
}
});
}
</script>
```
此段代码定义了一个基于 Element Plus 的弹窗组件[^1],并实现了双向绑定可见性的功能和简单的校验机制[^2]。
#### 修改父组件 `ParentComponent.vue` 使用该自定义弹窗组件
在父组件中通过属性传递控制子组件的状态,并监听来自子组件的消息来获取用户输入的数据。
```vue
<template>
<div class="parent-component">
<button @click="openDialog()">打开弹窗</button>
<ChildComponent
:model-value="isShow"
@update:model-value="val => isShow=val"
@submit="onSubmit"/>
<p>收到的信息:{{ receivedData }}</p>
</div>
</template>
<script setup>
import ChildComponent from './components/DialogComponent.vue';
import { ref } from 'vue';
let isShow = ref(false);
function openDialog(){
isShow.value=true;
}
let receivedData=ref('');
function onSubmit(data){
receivedData.value=data.name;
}
</script>
```
上述代码展示了如何利用 `.sync`修饰符简化父子间通信的过程,在点击按钮时触发弹窗显示;同时接收由子组件发出的提交事件以更新页面上的数据显示。
阅读全文
相关推荐


















