需求:父组件点击按钮后打开弹窗,但是因为弹窗内容巨多,直接提取出来,只要在父组件点击时才显示弹窗,并且传递值给弹窗做数据回显,编辑或者新增功能都可以。
1.首先建立父子关系
创建个弹窗组件dialog.vue,把弹窗内容丢进去
父组件引入注册挂载,并且设置v-if的值,默认为false,ref也要设置,绑定节点,点击的时候需要通过ref传递函数传值给子组件
<Dialog v-if="showDialog" ref="dialogData"></Dialog>
import Dialog from './dialog.vue';
export default {
components: {
Dialog
},
}
2.父组件写内容,点击传递当前行给子组件
父组件关键代码,init函数并且传当前行给子组件,完整代码最后贴
openDialog(row) {
this.showDialog = true;
this.$nextTick(() => {
// 每次都传递当前行数据
this.$refs.dialogData.init(row);
});
}
3.弹窗自组件在methods接受父组件传值
init(rowdata){
//打开弹窗
this.dialogVisible = true;
//接收父组件的值
this.data=rowdata
console.log(this.data,'接受传递的值');
},
4.父组件完整代码
<template>
<div class="content-box">
<div class="container">
<h1>弹窗的拆分</h1>
<el-table :data="tableData" style="width: 100%" max-height="250">
<el-table-column fixed prop="date" label="日期" width="150"> </el-table-column>
<el-table-column prop="name" label="姓名" width="120"> </el-table-column>
<el-table-column prop="province" label="省份" width="120"> </el-table-column>
<el-table-column label="操作" width="120">
<template slot-scope="scope">
<el-button @click.native.prevent="openDialog(scope.row)" type="text" size="small">
打开弹窗
</el-button>
</template>
</el-table-column>
</el-table>
<Dialog v-if="showDialog" ref="dialogData"></Dialog>
</div>
</div>
</template>
<script>
import Dialog from './dialog.vue';
export default {
components: {
Dialog
},
data() {
return {
showDialog: false,
tableData: [
{
date: '2016-05-03',
name: '王小虎',
province: '上海'
},
{
date: '2022-12-11',
name: '张三',
province: '武汉'
},
{
date: '2016-05-03',
name: '李四',
province: '上海'
}
]
};
},
mounted() {},
methods: {
openDialog(row) {
this.showDialog = true;
this.$nextTick(() => {
// 每次都传递当前行数据
this.$refs.dialogData.init(row);
});
}
}
};
</script>
<style lang="scss" scoped></style>
5.子组件完整代码
操作都在子组件完成,包括编辑接口调用,父组件只是传值和打开弹窗,其他不做操作
<template>
<el-dialog
title="提示"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose">
{{ data }}
<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 {
data() {
return {
dialogVisible: false,
data:{}
};
},
mounted() {
},
methods: {
init(rowdata){
this.dialogVisible = true;
this.data=rowdata
console.log(this.data,'接受传递的值');
},
handleClose(done) {
this.$confirm('确认关闭?')
.then(_ => {
done();
})
.catch(_ => {});
}
}
};
</script>
<style lang="scss" scoped>
</style>
文章到此结束,希望对你有所帮助~