Vite/Vue3/Typescript VueUse: onClickOutside problem

269 Views Asked by At

I use Vue3 w/Vite and Typescript and would like to implememnt the VueUse onClickOutside composable something like this (a simplified code):

<template>
    <div>
        <div
            @click="isShow = !isShow"
            ref="ignoreElRef"
        >
            <div
                v-if="isShow"
                v-on-click-outside="onClickOutsideHandler"
            >
                ...
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, Ref } from 'vue'
import { vOnClickOutside } from '@vueuse/components'

//handle toggle
const isShow = ref(false)

const ignoreElRef: Ref<HTMLElement | null> = ref(null)
const onClickOutsideHandler = [
    () => {
        isShow.value = false
    },
    {
        ignore: [ignoreElRef],
    },
]

</script>

I got the following error message:

Argument of type '((() => void) | { ignore: Ref<HTMLElement | null>[]; })[]' is not assignable to parameter of type 'OnClickOutsideHandler<{ detectIframe: false; }> | [(evt: any) => void, OnClickOutsideOptions]'.
  Type '((() => void) | { ignore: Ref<HTMLElement | null>[]; })[]' is not assignable to type 'OnClickOutsideHandler<{ detectIframe: false; }>'.ts(2345)

How should I rewrite the onClickOutsideHandler function to fix this issue? I tried in several way but there is no solution found.

Thank you in advance!

2

There are 2 best solutions below

1
yoduh On

Your handler should be a function, then the type for it would be OnClickOutsideHandler imported from @vueuse/core

<script setup lang="ts">
import { ref, Ref } from 'vue'
import { vOnClickOutside } from '@vueuse/components'
import type { OnClickOutsideHandler } from '@vueuse/core'

//handle toggle
const isShow = ref(false)

const ignoreElRef: Ref<HTMLElement | null> = ref(null)
const onClickOutsideHandler: OnClickOutsideHandler = () => {
  isShow.value = false
}
</script>
0
Mathieu Laurent On

A solution

<script setup lang="ts">
import { ref, Ref } from 'vue'
import { vOnClickOutside } from '@vueuse/components'
import type { OnClickOutsideOptions } from '@vueuse/core'


// handle toggle
const isShow = ref(false)

const ignoreElRef: Ref<HTMLElement | null> = ref(null)
const onClickOutsideHandler: [(evt: any) => void, OnClickOutsideOptions] = [
    (evt: any) => {
        isShow.value = false
    },
    {
        ignore: [ignoreElRef],
    },
]

</script>