需求:父页面的按钮弹出一个对话框,子页面进行操作后,子页面关闭或子页面关闭后返回值给父页面。
方法:有两种方法。
第一种:watch
第二种:ref
父页面具体代码如下:
//父页面
<template>
<div>
<a-button @click="handleBtnExport()">弹出对话框</a-button>
<ExportModal
:AlertParams="myAlertParams"
:exportVisible="myExportVisible"
@changeShow="changedShow"
/>
</div>
</template>
<script>
import ExportModal from './exportModal.vue';
export default {
name:'ParentDiv',
components:{ExportModal},
data(){
return{
myAlertParams:null,
myExportVisible:false
}
},
methods:{
handleBtnExport(){
this.myAlertParams={
p1:'1',
p2:'2'
}
this.myExportVisible = true;//打开Modal
},
changedShow(data) {//子页emit
if (data === 'false') {
this.myExportVisible = false;
} else {
this.myExportVisible = true;
}
},
},
};
</script>
子页面:
<template>
<a-modal v-model:visible="modalVisible" title="弹出对话框" @ok="handleOK" @cancel="handleClose">
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
</a-modal>
</template>
<script>
import { defineComponent, ref, onMounted, reactive, toRefs, watch } from 'vue';
export default defineComponent({
name:'ExportModal',
props: { exportVisible: { type: Boolean, default: false }, AlertParams: {} }, //向父组件设置属性
emits:['changeShow'],
setup(porps,{emit}){
let modalVisible = ref(false);
const param = ref({});//接收父组件传来的参数值
// 监听 exportVisible 改变
watch(
() => props.exportVisible,
(val) => {
modalVisible.value = val;
if (val == true) {
var pp = {
p1: props.AlertParams.p1,
p2: props.AlertParams.p2,
};
param.value = pp;//传值过程
}
},
);
function handleOK(){
modalVisible.value = false;
emit('changeShow', 'false'); //执行父组件事件,改变exportVisible属性值
}
function handleClose() {
// 子组件调用父组件方法,并传递参数
modalVisible.value = false;
emit('changeShow', 'false');
}
return{
modalVisible, handleOK, handleClose
}
}
});
</script>
第二种方法:
先在父页面定义子组件ref
const ExportModalRef = ref(null);
再在父页面的“弹出对话框事件中”利用$refs,调用子组件方法:
this.$refs.ExportModalRef.showModal();
具体代码有空了再加吧