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 功能。
