Skip to content
文章目录

给任意vue组件添加install方法用于全局注册

ts
/**
 * @file: withInstall.ts
 */
import { App, Component, Plugin } from 'vue'

export type SFCInstall<T extends Component> = T & Plugin

/**
 * 给任意Vue组件添加install方法,以便全局安装使用
 *
 * @param   {T<T>}           comp  Vue组件对象
 *
 * @return  {SFCInstall<T>}        [return description]
 */
export function withInstall<T extends Component>(comp: T): SFCInstall<T> {
  ;(comp as SFCInstall<T>).install = function (app: App) {
    const { name } = comp as { name: string }
    app.component(name, comp)
  }
  return comp as SFCInstall<T>
}

使用

ts
import { withInstall } from './withInstall.ts'
import MyComp from './MyComp.vue'

export default withInstall(MyComp)