1.使用组件传参和计算属性来控制弹窗
父组件
<template>
<el-button @click="goTest('test')">测试</el-button>
<el-button @click="goTest('edit',data)">编辑</el-button>
<Test v-model:dialogVisible="testVisible" :currentData="currentData" @update-query="onSearch"/>
</template>
<script setup>
import Test from './test.vue'
const testVisible = ref(null)
const currentData = ref(null)
const goTest = (type,row = null) => {
testVisible.value = true
currentData.value = type === 'edit' ? row : null
}
const onSeach = async() => {
await 接口()
}
</script>
子组件
<template>
<el-dialog
v-model="visible"
:title="title"
width="550px"
center
:destroy-on-close="true"
@open="handleOpen"
@closed="handleClose"
>
<el-form>
<el-form-item label="测试">
<el-input v-model="test" />
</el-form-item>
</el-form>
</el-dialog>
</template>
<script setup>
const emit = defineEmits(['update:dialogVisible', 'updateQuery'])
const props = defineProps({
dialogVisible: {
type: Boolean,
default: false
},
currentData: {
type: [Object, Array, null, String],
default: null
}
})
const searchForm = reactive({
test: null
})
const visible = computed(() => {
return props.dialogVisible
})
const handleOpen = () => {
if(props.currentData.id) {
Object.assign(searchForm, props.currentData)
}
}
const handleClose = () => {
Object.keys(searchForm).forEach(key => {
searchForm[key] = null
})
emit('update:dialogVisible', false)
emit('updateQuery')
}
</script>
2.通过ref控制 defineExpose
父组件
<template>
<el-button @click="goTest('test')">测试</el-button>
<el-button @click="goTest('edit',data)">编辑</el-button>
<Test ref="dialogRef" @update-query="onSearch"/>
</template>
<script setup>
import Test from './test.vue'
const dialogRef = ref(null)
const goTest = (type,row = null) => {
dialogRef.value.openDialog(type, row)
}
const onSeach = async() => {
await 接口()
}
</script>
子组件
<script setup>
const visible = ref(false)
const emit = defineEmits(['updateQuery'])
const searchForm = reactive({
test: null
})
const openDialog = (type,data = null) => {
visible.value = true
if(type==="edit") {
Object.assign(searchForm, data)
}
}
const handleClose = () => {
Object.keys(searchForm).forEach(key => {
searchForm[key] = null
})
visible.value = false
emit('updateQuery')
}
defineExpose({ openDialog })
</script>