欣迪
person holding apple magic mouse

vue 3 的 composition API 使用後,已經不再推薦 mixin,取而代之的是 Composables。

官方文件: https://vuejs.org/guide/reusability/composables.html

這樣的做法其實好處多多,不用每次為了一個小功能寫一大包 mixin,在獨立的 scope 下也能解決命名衝突的問題。導入上也更加簡潔。

這邊就實作做一個 click outside 功能。

兩個變數:

  • elRef : 使用 ref 取得的 dom
  • onClickOutside: click outside 後的 callback
// handleClickOutSide
import { onMounted, onBeforeUnmount } from 'vue';

const handleClickOutSide = (elRef, onClickOutside) => {
  if (!elRef) return;
  const handler = (e) => {
    // 注意一下,如果是在 setup 中使用 vue.ref 取得 dom,那麼必須使用 el.value 提取 dom
    const el = elRef.value;
    if (!el) return;
    if (!el.contains(e.target)) {
      if (typeof onClickOutside === 'function') {
        onClickOutside();
      }
    }
  };
  onMounted(() => {
    window.addEventListener('click', handler);
  });
  onBeforeUnmount(() => {
    window.removeEventListener('click', handler);
  });
};

export default handleClickOutSide;

在 component 中使用

<!-- Example.vue -->
<template>
  <div ref="el">
  	bla bla...
  </div>
</template>
// Example.vue
// secript setup 或 setup () 內使用
import handleClickOutSide from './handleClickOutSide';

const el = ref(null);

handleClickOutSide(el, () => {
	console.log('it works')
});

這樣即可完成 click outside 功能。

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。