问题
因为业务须要,所以呈现了不停弹出ElMessageBox
的这种状况,代码如下:
<template> <el-select v-model="form.type" @focus="onFocus"> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" /> </el-select></template><script>import ...export default defineComponent({ setup() { const form = ref({}) const options = ref([]) const onFocus = () => { if (!form.value.cate) { ElMessageBox.alert('请先抉择分类', '提醒', { confirmButtonText: '好的', }) } } return { form, options, onFocus, } }})</script>
解决办法:
起初想到应该是ElMessageBox
组件让el-select
不停地处在focus
的状态上,所以才会不停地触发focus
事件,陷入对话框死循环。所以我就在触发focus
事件的结尾,增加让el-select
失去焦点的办法,刚好官网文档里,el-select
就有一个blur()
办法。
这个时候须要用到ref
了,而在vue3
的setup
里调用$refs
的形式,我先是用了 getCurrentInstance
,然而不晓得为何返回的是null
,所以最终用上面的办法解决了反复弹出的问题。
<template> <el-select v-model="form.type" @focus="onFocus" ref="selectRef"> <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" /> </el-select></template><script>import ...export default defineComponent({ setup() { const form = ref({}) const options = ref([]) const selectRef = ref(null) const onFocus = () => { if (!form.value.cate) { ElMessageBox.alert('请先抉择分类', '提醒', { confirmButtonText: '好的', callback: action => { //被动失去焦点的的办法加在这里是有效的。 } }) selectRef.value.blur() //就是这一句, } } return { form, options, onFocus, selectRef, } }})</script>