父组件打开子组件的el-dialog的方式?
方法一、V-model
// Parent.vue
<script setup lang="ts">
import { ref, version as vueVersion } from 'vue'
import { version as epVersion } from 'element-plus'
import { ElementPlus } from '@element-plus/icons-vue'
import Child from "./Child.vue"
const show = ref(false);
</script>
<template>
<el-button @click="show=true">show</el-button>
<Child v-model:show="show" />
</template>
// Child.vue
<script setup>
import {defineModel} from "vue"
const show = defineModel("show");
</script>
<template>
<el-dialog v-model="show">
This is model
</el-dialog>
</template>
方法二、ref + defineExpose
// parent.vue
<script setup lang="ts">
import { ref, version as vueVersion } from 'vue'
import { version as epVersion } from 'element-plus'
import { ElementPlus } from '@element-plus/icons-vue'
import Child from "./Child.vue"
const childRef = ref(null);
function open() {
childRef.value.open();
}
</script>
<template>
<el-button @click="open()">show</el-button>
<Child ref="childRef"/>
</template>
// Child.vue
<script setup>
import {defineModel, ref, onMounted, defineExpose} from "vue"
const show = ref(false);
function open() {
show.value = true;
}
defineExpose({open})
</script>
<template>
<el-dialog v-model="show">
This is model
</el-dialog>
</template>
- 还有其他方式吗?
- 哪种方法是最好的(或者说最佳实践)?
如果是封装的通用组件,比如说UI库。那么推荐第一种的方式(使用
props
+emit
的思路)。只传入show
属性,然后再按照具体的情况使用emit
抛出一些on-show
、on-close
等等的事件。如果是基于UI组件库再次封装的业务弹窗组件,那么我推荐的是类似第二种的方式。子组件暴露出来
open()
方法和close()
等方法在父级调用,并且在子组件内自己操作修改show
属性和一些其他业务(在打开弹窗的同时很可能需要配合做一些业务处理,比如说一些表单内组件的初始化操作)。