Search code examples
javascriptvue.jsbuttonvueuse

VueUse OnClickOutside ignore options not working


i'm using OnClickOutside from VueUse, the vue code is:

<template>
  <button class="button" id="button1" ref="tempRef">AAA</button>
  <OnClickOutside id="clickOutside" :options="{ ignore: [tempRef] }" @trigger="console.log(tempRef)">
    <button class="button" id="button2">BBB</button>
  </OnClickOutside>
</template>

<script setup>
import { OnClickOutside } from '@vueuse/components'
import { ref } from 'vue'

const tempRef = ref()
</script>

So, my expectation is, when I click button1, the OnClickOutside won't be triggered since tempRef is inside the ignore. But, it turns out, the console still output tempRef when I clicked button1. I've tried some adjustments but nothing works. Do I misunderstand how to use ignore in OnClickOutside? How to fix this? Thx for the help

Here is the documentation for easy access: https://vueuse.org/core/onClickOutside/


Solution

  • Refs are automatically unwrapped when used in the template, so instead of providing the ignore option a ref object, it's being provided the inner non-ref value. If you provide an options object created in your <script> code it should work:

    <template>
      <button id="button1" ref="tempRef" class="button">AAA</button>
      <OnClickOutside
        id="clickOutside"
        :options="options"
        @trigger="console.log(tempRef)"
      >
        <button id="button2" class="button">BBB</button>
      </OnClickOutside>
    </template>
    
    <script setup>
    import { OnClickOutside } from '@vueuse/components'
    import { ref } from 'vue'
    
    const tempRef = ref()
    
    const options = { ignore: [tempRef] }
    </script>
    

    The ignore option can also be given a selector string, so you could use that as an alternative if you want a template-only solution:

    <OnClickOutside
      id="clickOutside"
      :options="{ ignore: ['#button1'] }"
      @trigger="console.log(tempRef)"
    >