想在<script setup>里直接使用一个click-outside组件,试了下面几种都不行:
xv-click-outside:不可用,测试版本3.2.0 ff
click-outside-vue3: 不可用,测试版本4.0.1
vue-click-outside: 不可用,测试版本1.1.0
可用版本:
onClickOutside | VueUse
唯一直接可以使用的版本。
使用方法:
安装vueuse component
npm i @vueuse/core @vueuse/components
在需要使用的vue文件中
import { vOnClickOutside } from '@vueuse/components'
注意,要以v开头,官方文档解释了以v开头的目的:
The reason for requiring the
v
prefix is because it is quite likely for a globally registered directive (e.g.v-focus
) to clash with a locally declared variable of the same name. Thev
prefix makes the intention of using a variable as a directive more explicit and reduces unintended "shadowing".
这样,html部分可以直接写:
<div id="ec-selector" v-if="showEcSelector" v-on-click-outside="hideEcSelector">
</div>
官方的文档有其他两种写法:
函数写法:
<script setup>
import { ref } from 'vue'
import { onClickOutside } from '@vueuse/core'const el = ref()function close () {/* ... */
}onClickOutside(el, close)
</script><template><div ref="el">Click Outside of Me</div>
</template>
和自定义组件写法:
<script setup>
import { OnClickOutside } from '@vueuse/components'function close () {/* ... */
}
</script><template><OnClickOutside @trigger="close"><div>Click Outside of Me</div></OnClickOutside>
</template>