需求:用户点击按钮,弹出框出现,弹出框里有确认&取消按钮,点击确认&取消&其他区域,弹出框消失。
文档上是这样写的此时你会发现,设置完visible,点击其他区域,弹出框不会消失!
项目是基于vue3+element-plus+TS,通过设置ref去解决,分两种情况:
一般情况
<template>
<el-popover trigger="click" ref="popoverRef" placement="top">
<p>Are you sure to delete this?</p>
<div style="text-align: right; margin: 0">
<el-button size="small" text @click="handleClose()">cancel</el-button>
<el-button size="small" type="primary" @click="handleClose()">confirm</el-button>
</div>
<template #reference>
<el-button>Delete</el-button>
</template>
</el-popover>
</template>
<script lang='ts'>
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const popoverRef = ref<any>(null);
// 关闭
const handleClose = () => {
popoverRef.value.hide();
};
return {
popoverRef,
handleClose,
};
},
});
</script>
在表格中循环
此情况ref不唯一 ,如果用上面的方法,会发现只有一个弹出框会消失,其余的都不会消失
<template>
<el-table :data="[]">
<el-table-column label="状态" align="center">
<template #default="{ row }">
<el-popover trigger="click" :ref="setRefs" placement="top">
<p>Are you sure to delete this?</p>
<div style="text-align: right; margin: 0">
<el-button size="small" text @click="handleClose()">cancel</el-button>
<el-button size="small" type="primary" @click="handleClose()">confirm</el-button>
</div>
<template #reference>
<el-button>Delete</el-button>
</template>
</el-popover>
</template>
</el-table-column>
</el-table>
</template>
<script lang='ts'>
import { defineComponent, ref, onBeforeUpdate } from 'vue';
export default defineComponent({
setup() {
const refs = ref<any[]>([]);
// 使用回调的方式收集
const setRefs = (el: any) => {
refs.value.push(el);
};
// 更新时-重置refs
onBeforeUpdate(() => {
refs.value = [];
});
// 关闭
const handleClose = () => refs.value.forEach(v => v.hide());
return {
setRefs,
handleClose,
};
},
});
</script>