说明
vue创建插件分为: 全局参数, 全局函数, 全局指令, 全局组件, 以及provide
代码
参考位置: src/plugins/demo/demo.ts
import type { App, Plugin } from 'vue'
export const DemoPlugin: Plugin = {
install(app: App, options: any) {
// 全局参数 $gValue
app.config.globalProperties.$gValue = options.value
// 全局函数 $translate(arg)
app.config.globalProperties.$translate = (key: string) => {
return key
}
// https://cn.vuejs.org/guide/reusability/custom-directives.html
// <div v-directive="123">
app.directive('directive', {
mounted(el: any, binding: Object, vnode: any, prevVnode: any) {
console.log(el, binding, vnode, prevVnode)
}
})
// 注册组件 <PluginDemo/>
app.component('PluginDemo', {
template: `<h1>{{$translate('测试')}}</h1><span>{{$gValue}}</span>`
})
// const gValue2 = inject('gValue2')
app.provide('gValue2', 'gValue2')
}
}
类型文件
参考位置如: src/plugins/demo/index.d.ts
需要把全局参数与函数注册一下
export {}
declare module 'vue' {
interface ComponentCustomProperties {
$gValue: ColoredText
$translate: (key: string) => string
}
}
调用
import { DemoPlugin } from './plugins/demo/demo'
app.use(DemoPlugin, {
value: 'value1'
})
参考使用
<template>
<PluginDemo></PluginDemo>
{{ $gValue }}
{{ gValue2 }}
{{ $translate('测试') }}
<div class="" v-directive="123"></div>
</template>
<script>
import { inject } from 'vue'
const gValue2 = inject('gValue2')
</script>
tsconfig
"include": ["env.d.ts", "src/**/*.vue", "src/**/*.ts"],