Vue3自定义插件

发布于:

#插件入门

插件是一个暴露install函数的对象,可以通过app.use(plugin)来安装
插件一般提供如下三个功能,提供一个或者多个
  1. 使用app.component()或app.directive()注册全局组件/指令
  2. 使用app.provide()全局注入
  3. 使用app.config.globalProperties添加全局属性或方法

#编写i18n插件

i18n插件,提供了全局的$t函数
见第四行,app即app实例,options是传入的参数,i18n插件options即字典
ts
import type { App } from 'vue' export default { install: (app: App, options: Object) => { app.provide('i18n', options) app.config.globalProperties.$t = (key: string) => key.split('.').reduce((pre: any, cur: string) => { if (!pre) throw new Error('需要传入字典') else if (!pre[cur]) throw new Error(`字典${cur}不存在`) return pre[cur] }, options) } }
注意:声明ts类型文件,需要一个默认导出
ts
export default {} declare module 'vue' { interface ComponentCustomProperties { $t: (key: string) => string } }