在 Typescript 中使用可被復(fù)用的 Vue Mixin功能
轉(zhuǎn)到用 Typescript 寫 Vue 應(yīng)用以后,經(jīng)過一輪工具鏈和依賴的洗禮,總算蹣跚地能走起來了,不過有一個很常用的功能 mixin,似乎還沒有官方的解決方案。
既想享受 mixin 的靈活和方便,又想收獲 ts 的類型系統(tǒng)帶來的安全保障和開發(fā)時使用 IntelliSense 的順滑體驗(yàn)。
vuejs 官方組織里有一個 'vue-class-component'
以及連帶推薦的 'vue-property-decorator'
,都沒有相應(yīng)實(shí)現(xiàn)。翻了下前者的 issue,有一條掛了好些時間的待做 feature 就是 mixin 的支持。
也不是什么復(fù)雜的事,自己寫一個吧。
后注:vue-class-component 6.2.0 開始提供 mixins 方法,和本文的實(shí)現(xiàn)思路相似。
實(shí)現(xiàn)
import Vue, { VueConstructor } from 'vue' export type VClass<T> = { new(): T } & Pick<VueConstructor, keyof VueConstructor> /** * mixins for class style vue component */ function Mixins<A>(c: VClass<A>): VClass<A> function Mixins<A, B>(c: VClass<A>, c1: VClass<B>): VClass<A&B> function Mixins<A, B, C>(c: VClass<A>, c1: VClass<B>, c2: VClass<C>): VClass<A&B&C> function Mixins<T>(c: VClass<T>, ...traits: Array<VClass<T>>): VClass<T> { return c.extend({ mixins: traits }) }
聲明 VClass<T> 可作為 T 的類構(gòu)造器。同時通過 Pick 拿到 Vue 的構(gòu)造器上的靜態(tài)方法(extend/mixin 之類),如此才能夠支持下面這段中的真正實(shí)現(xiàn),通過調(diào)用一個 Vue 的子類構(gòu)造器上的 extend 方法生成新的子類構(gòu)造器。
function Mixins<T>(c: VClass<T>, ...traits: Array<VClass<T>>): VClass<T> { return c.extend({ mixins: traits }) }
至于 ABC 這個純粹是類型聲明的體力活了。
使用
實(shí)際使用時:
import { Component, Vue } from 'vue-property-decorator' import { Mixins } from '../../util/mixins' @Component class PageMixin extends Vue { title = 'Test Page' redirectTo(path: string) { console.log('calling reidrectTo', path) this.$router.push({ path }) } } interface IDisposable { dispose(...args: any[]): any } class DisposableMixin extends Vue { _disposables: IDisposable[] created() { console.log('disposable mixin created'); this._disposables = [] } beforeDestroy() { console.log('about to clear disposables') this._disposables.map((d) => { d.dispose() }) delete this._disposables } registerDisposable(d: IDisposable) { this._disposables.push(d) } } @Component({ template: ` <div> <h1>{{ title }}</h1> <p>Counted: {{ counter }}</p> </div> ` }) export default class TimerPage extends Mixins(PageMixin, DisposableMixin) { counter = 0 mounted() { const timer = setInterval(() => { if (this.counter++ >= 3) { return this.redirectTo('/otherpage') } console.log('count to', this.counter); }, 1000) this.registerDisposable({ dispose() { clearInterval(timer) } }) } } count to 1 count to 2 count to 3 calling reidrectTo /otherpage about to clear disposables
注意到直接 extends Vue 的 DisposableMixin 并不是一個有效的 Vue 組件,也不可以直接在 mixins 選項里使用,如果要被以 Vue.extend 方式擴(kuò)展的自定義組件使用,記住使用 Component 包裝一層。
const ExtendedComponent = Vue.extend({ name: 'ExtendedComponent', mixins: [Component(DisposableMixin)], })
Abstract class
在業(yè)務(wù)系統(tǒng)中會使用到的 Mixin 其實(shí)多數(shù)情況下會更復(fù)雜,提供一些基礎(chǔ)功能,但有些部分需要留給繼承者自行實(shí)現(xiàn),這個時候使用抽象類就很合適。
abstract class AbstractMusicPlayer extends Vue { abstract audioSrc: string playing = false togglePlay() { this.playing = !this.playing } } class MusicPlayerA extends AbstractMusicPlayer { audioSrc = '/audio-a.mp3' } class MusicPlayerB extends AbstractMusicPlayer { staticBase = '/statics' get audioSrc() { return `${this.staticBase}/audio-b.mp3` } }
但抽象類是無法被實(shí)例化的,并不滿足 { new(): T }
這個要求,因此只能被繼承,而不能被混入,由于同樣的原因,抽象類也無法被 'vue-class-component'
的 Component 函數(shù)裝飾。
這時候只好將實(shí)現(xiàn)了的功能寫入 Mixin 中,待實(shí)現(xiàn)的功能放到接口里,讓具體類來實(shí)現(xiàn)。
interface IMusicSourceProvider { audioSrc: string } /** * @implements IPlayerImplementation */ class PlayerMixin extends Vue { /** @abstract */ audioSrc: string logSrc() { console.log(this.audioSrc) } } interface IPlayerImplementation extends IMusicSourceProvider {} class RealPlayer extends Mixins(PlayerMixin) implements IPlayerImplementation { audioSrc = '/audio-c.mp3' }
這種欺騙編譯器的方式其實(shí)還是比較拙劣的,如果一個具體類繼承了 PlayerMixin,卻沒有顯示聲明實(shí)現(xiàn) IPlayerImplementation ,編譯器無法告訴你這個錯誤。我們只能在代碼里小心翼翼寫上注釋,期待使用者不要忘了這件事。
總結(jié)
以上所述是小編給大家介紹的在 Typescript 中使用可被復(fù)用的 Vue Mixin功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
在Vue3中使用provide和inject進(jìn)行依賴注入的代碼詳解
在現(xiàn)代前端開發(fā)中,Vue.js已經(jīng)成為了非常流行的框架之一,它提供了極大的靈活性和可維護(hù)性,今天我們要探討的是Vue?3中的provide和inject功能,這是一種用于在組件樹中進(jìn)行依賴注入的方法,需要的朋友可以參考下2024-06-06vue2.x element-ui實(shí)現(xiàn)pc端購物車頁面demo
這篇文章主要為大家介紹了vue2.x element-ui實(shí)現(xiàn)pc端購物車頁面demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06vue3中unplugin-auto-import自動引入示例代碼
unplugin-auto-import 這個插件是為了解決在開發(fā)中的導(dǎo)入問題,下面這篇文章主要給大家介紹了關(guān)于vue3中unplugin-auto-import自動引入的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02vue2.0實(shí)現(xiàn)音樂/視頻播放進(jìn)度條組件
這篇文章主要為大家詳細(xì)介紹了vue2.0實(shí)現(xiàn)音樂和視頻播放進(jìn)度條組件的思路及具體實(shí)現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06antd?vue中,如何在form表單中的自定義組件使用v-decorator
antd?vue中,在form表單中的自定義組件使用v-decorator問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04