一段代码给 vue 的应用实例添加全局功能。它的格式是一个暴露出 install() 方法的 Object,或者一个 function。
它没有严格的限制,一般有以下几种功能。
vue3已移除)等。config.globalProperties 来添加 app 实例方法。编写插件代码
import type { App } from 'vue';
const plugins = {
install: (app: App) => {
app.config.globalProperties.$test = () => {
console.log('this is a test plugin !');
};
},
};
export default plugins;注册插件
import { createApp } from 'vue';
import App from './App.vue';
import testPlugin from './test.plugin';
const app = createApp(App);
app.use(testPlugin);
app.mount('#app');使用插件方法
import { onMounted, getCurrentInstance } from 'vue';
onMounted(() => {
const vm = getCurrentInstance()
vm?.appContext.config.globalProperties.$test()
})编写插件代码
import type { App } from 'vue';
import GlobalComponent from './components/GlobalComponent.vue';
const plugins = {
install: (app: App) => {
app.component('global-component', GlobalComponent);
},
};
export default plugins;编写插件代码
import type { App } from 'vue';
const plugins = {
install: (app: App) => {
app.provide('test', { message: 'test plugin' });
},
};
export default plugins;使用插件内容
import { inject } from 'vue';
const test = inject('test')
console.log('🚀🚀 ~ test', test);使用 imooc-cli 创建项目,选择项目基础模板,然后把下面几个文件转移到项目中。
所有组件一次性全部导入作为插件使用
import LegoComponent from 'lego-component'
app.use(LegoComponent);index.tsinstall 函数,循环调用 app.componentinstall 函数单个组件导入作为插件使用
import { LText } from 'lego-component';
app.use(LText);
// 或者
app.component(LText.name,LText)index.ts 文件install 方法的 Object整个项目的入口文件
// src\index.ts
import type { App } from 'vue';
// 组件对象
import LText from './components/LText';
import LImage from './components/LImage';
// 组件列表
const components = [LText, LImage];
// 遍历 components 注册全局组件
const install = (app: App) => {
components.forEach((c) => {
app.component(c.name, c);
});
};
// 按需导出
export { LText, install };
// 默认整体导出
export default {
install,
};单个组件的入口文件
// src\components\LText\index.ts
import type { App } from 'vue';
import LText from './LText.vue';
// 注册单个组件的插件
LText.install = (app: App) => {
app.component(LText.name, LText);
};
export default LText;