Skip to content

插件开发

INFO

你可以继续开发一些自定义插件来满足个性化业务场景

插件-函数形式

定义为函数时,它接收一个参数,即 context

typescript
export function myPlugin(context){
  context.router // vue-router 实例
  context.runWithApp // 运行一个函数,在 router.install 时调用,接收 vue 实例作为参数
  context.onUnmount // 注册一个函数,当 vue 实例被卸载时调用
}

你还可以给该函数返回清理钩子,当用户执行 router.runPluginsCleanup 时被调用

typescript
export function myPlugin(context){
  context.router // vue-router 实例
  context.runWithApp // 运行一个函数,在 router.install 时调用,接收 vue 实例作为参数
  context.onUnmount // 注册一个函数,当 vue 实例被卸载时调用
  return {
    onCleanup:() => {
      // 可以在这里做一些清理工作
    }
  }
}

你可以给函数定义一个静态属性 resolveOptions,它会在路由实例创建前被调用,可以对传递给 createRouter 中的 options 进行修改

typescript
import type { RouterOptions } from 'vue-router'

export function myPlugin(context){
  context.router // vue-router 实例
  context.runWithApp // 运行一个函数,在 router.install 时调用,接收 vue 实例作为参数
  context.onUnmount // 注册一个函数,当 vue 实例被卸载时调用
  return {
    onCleanup:() => {
      // 可以在这里做一些清理工作
    }
  }
}

myPlugin.resolveOptions = (options: RouterOptions) => {
  // 可以在这里对 options 做一些处理
  return options
}

插件-对象形式

typescript
const myPlugin = {
  install(context){
    context.router // vue-router 实例
    context.runWithApp // 运行一个函数,在 router.install 时调用,接收 vue 实例作为参数
    context.onUnmount // 注册一个函数,当 vue 实例被卸载时调用
    return {
      onCleanup:() => {
        // 可以在这里做一些清理工作
      }
    }
  },
  resolveOptions(options){
    // 可以在这里对 options 做一些处理
    return options
  }
}

Typescript

插件的类型提示请参考 Admin 中任一插件。