前言
学过vue的小伙伴应该都知道,父子组件通信一般使用props,下面我们使用ref代替props来实现一个弹窗功能
一、父组件
<template>
<div>
<el-button type="primary" @click="handleOpen">打开弹窗</el-button>
<!-- 弹窗-->
<son-model ref="model"></son-model>
</div>
</template>
<script>
import sonModel from "@/components/sonModel";
export default {
name: "Father",
components:{
sonModel
},
methods:{
handleOpen(){
// 通过ref拿到弹窗组件,然后直接调用弹窗组件的open方法
this.$refs.model.open()
// 修改弹窗组件的title
this.$refs.model.title = '弹窗①号'
}
}
}
</script>
<style scoped>
</style>
二、子组件
<template>
<el-dialog
:title="title"
:visible.sync="dialogVisible"
width="30%">
<span>这是一段信息</span>
<span slot="footer" class="dialog-footer">
<el-button @click="handleCancel">取 消</el-button>
<el-button type="primary" @click="handleSubmit">确 定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
name: "sonModel",
data(){
return {
dialogVisible: false,
title:'',
}
},
methods:{
// 打开弹窗
open(){
this.dialogVisible = true
},
handleSubmit(){
// 做一些提交的逻辑操作
this.dialogVisible = false
},
handleCancel(){
this.dialogVisible = false
}
},
}
</script>
<style scoped>
</style>
总结
巧妙的使用ref可以简化我们的代码。