问题
因为业务需要,所以出现了不停弹出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>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。