vue3 composition api的click-outside选择

想在<script setup>里直接使用一个click-outside组件,试了下面几种都不行: 

x​​​​​​​v-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. The v 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>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百家饭OpenAPI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值