看過 Vue 源碼的同學可以知道,<keep-alive>、<transition>、<transition-group>等組件
組件的實現是一個對象,注意它有一個屬性 abstract 為 true,表明是它一個抽象組件。
Vue 的文檔沒有提這個概念,在抽象組件的生命周期過程中,我們可以對包裹的子組件監聽的事件進行攔截,也可以對子組件進行 Dom 操作,從而可以對我們需要的功能進行封裝,而不需要關心子組件的具體實現。
<!-- more -->
下面實現一個 debounce 組件,對子組件的 click 事件進行攔截
核心代碼如下:
<script>import {get, debounce, set} from 'loadsh';export default { name: 'debounce', abstract: true, //標記為抽象組件 render() { let vnode = this.$slots.default[0]; // 子組件的vnode if (vnode) { let event = get(vnode, `data.on.click`); // 子組件綁定的click事件 if (typeof event === 'function') { set(vnode, `data.on.click`, debounce(event, 1000)); } } return vnode; }};</script>使用
<debounce> <button @click="clickHandler">測試</button></debounce>
可以看到,按鈕的 click 事件已經加上了去抖(debounce)操作。
我們可以進一步對 debounce 組件進行優化。
<script>import {get, debounce, set} from '@/utils';export default { name: 'debounce', abstract: true, //標記為抽象組件 props: { events: String, wait: { type: Number, default: 0 }, options: { type: Object, default() { return {}; } } }, render() { let vnode = this.$slots.default[0]; // 子組件的vnode if (vnode && this.events) { let eventList = this.events.split(','); eventList.forEach(eventName => { let event = get(vnode, `data.on[${eventName}]`); // 子組件綁定的click事件 if (typeof event === 'function') { /** * 加上debounce操作, 參數與 lodash 的debounce完全相同 */ set(vnode, `data.on[${eventName}]`, debounce(event, this.wait, this.options)); } }); } return vnode; }};</script>使用
<debounce events="click" :wait="250" :options="{maxWait: 1000}"> <button @click="clickHandler">測試</button></debounce>我們同樣可以為輸入框的 input 事件進行 debouce 操作
<debounce events="input" :wait="250" :options="{maxWait: 1000}"> <input @input="inputandler" placeholder="輸入關鍵字進行搜索" /></debounce>以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。
|
新聞熱點
疑難解答
圖片精選