父组件:
<!-- 父组件 -->
<template>
<dialog-demo
v-model="dialogFormVisible"
@closeDialog="dialogFormVisible= false"
/>
</template>
<script>
import dialogDemo from "./components/dialog-demo"; // 引入子组件
export default {
name: "father",
components: {
dialogDemo ,
},
data() {
return {
dialogFormVisible: false, //是否展示详情弹窗
};
},
methods: {},
},
};
</script>
子组件(写法1 利用 value 实现双向绑定【推荐】 ):
1、利用computed的get和set属性实现数据实时监听
<!-- 子组件 -->
<template>
<!-- 弹窗新增 -->
<el-dialog
:close-on-click-modal="false"
title="详情"
:visible.sync="dialogFormVisible"
width="640px"
>
...弹窗内容省略
<div
slot="footer"
class="dialog-footer clearfix"
align="center"
>
<el-button
class="two-words fr"
size="small"
@click="closeDialog"
>关 闭</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
name: "dialog-demo",
props: {
value: {
type: Boolean,
default: false,
},
},
computed: {
dialogFormVisible: {
// 利用计算属性动态设置外部v-model绑定值
set(val) {
this.$emit("input", val);
},
// 利用计算属性动态获取外部v-model绑定值
get() {
return this.value;
},
},
},
data() {
return {};
},
methods: {
closeDialog() {
this.$emit("closeDialog");
},
},
};
</script>
2、利用watch实现数据实时监听
<!-- 子组件 -->
<template>
<!-- 弹窗新增 -->
<el-dialog
:close-on-click-modal="false"
title="详情"
:visible.sync="dialogFormVisible"
width="640px"
>
...弹窗内容省略
<div
slot="footer"
class="dialog-footer clearfix"
align="center"
>
<el-button
class="two-words fr"
size="small"
@click="closeDialog"
>关 闭</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
name: "dialog-demo",
props: {
value: {
type: Boolean,
default: false,
},
},
watch: {
// 监听到外部v-model绑定值变化后初始化和赋值
value: {
immediate: true, // 第一次数据传入后立即监听
deep: true, // 深度监听
handler(val, oval) {
this.dialogFormVisible = val
},
},
// 监听到内部值变化后传给外部v-model绑定值
dialogFormVisible (val, oval) {
this.$emit("input", val);
},
},
data() {
return {
dialogFormVisible: false
};
},
methods: {
closeDialog() {
this.$emit("closeDialog");
},
},
};
</script>
子组件(写法2 利用 model 实现双向绑定):
<!-- 子组件 -->
<template>
<!-- 弹窗新增 -->
<el-dialog
:close-on-click-modal="false"
title="详情"
:visible.sync="dialogFormVisible"
width="640px"
>
...弹窗内容省略
<div
slot="footer"
class="dialog-footer clearfix"
align="center"
>
<el-button
class="two-words fr"
size="small"
@click="closeDialog"
>关 闭</el-button>
</div>
</el-dialog>
</template>
<script>
export default {
name: "dialog-demo",
model: {
prop: 'dialogFormVisible',
event: 'change'
},
props: {
dialogFormVisible: {
type: Boolean,
default: false
},
},
data() {
return {};
},
methods: {
closeDialog() {
this.$emit("closeDialog");
},
},
};
</script>
网友评论