第一种:
父组件传入一个值控制,子组件内部监听传入的值,然后赋值给内部的值进行更改。还需要在@close关闭方法进行$emit父组件的值传入false以关闭对话框。
1、组件内部
<template>
<el-dialog
title="提示"
:visible.sync="dialogVisible"
width="30%"
@close="$emit('update:childShow', false)"
>
<span>这是一段信息</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
props:{
childShow:{
type:Boolean,
default:false
}
},
data(){
return {
dialogVisible:false
}
},
watch:{
childShow(val){
this.dialogVisible = val
}
}
};
</script>
2、页面使用
<template>
<div>
<el-button @click="directoryShow = true">显示</el-button>
<showDialog :childShow.sync="directoryShow" />
</div>
</template>
<script>
// 别名引入写法
import showDialog from "@/components/showDialog.vue";
export default {
components: { showDialog },
data(){
return {
directoryShow:false
}
}
};
</script>
第二种:
直接在父组件用if判断,子组件内部保持一直显示状态,需要关闭对话框时只需$emit调父组件的方法,在父组件上将if的值设置为false即可。
1、组件内部
<template>
<el-dialog
title="提示"
:visible.sync="dialogVisible"
width="30%"
@close="$emit('close')"
>
<span>这是一段信息</span>
<span slot="footer" class="dialog-footer">
<el-button @click="$emit('close')">取 消</el-button>
<el-button type="primary" @click="$emit('close')">确 定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
data(){
return {
dialogVisible:true
}
}
};
</script>
<style></style>
2、父组件使用
<template>
<div>
<el-button @click="directoryShow = true">显示</el-button>
<showDialog v-if="directoryShow" @close="directoryShow = false" />
</div>
</template>
<script>
import showDialog from "@/components/showDialog.vue";
export default {
components: { showDialog },
data() {
return {
directoryShow: false,
};
},
};
</script>
<style></style>