什么是插件
插件 (Plugins) 是一种能为 Vue 添加全局功能的工具代码
插件的组成
- 一个插件可以是一个拥有
install()方法的对象,也可以直接是一个安装函数本身。 - 安装函数会接收到安装它的应用实例和传递给
app.use()的额外选项作为参数
插件可能存在的应用场景
- 通过 app.component() 和 app.directive() 注册一到多个全局组件或自定义指令。
- 通过 app.provide() 使一个资源可被注入进整个应用。
- 向 app.config.globalProperties 中添加一些全局实例属性或方法
- 一个可能上述三种都包含了的功能库 (例如 vue-router)
使用示例:
一个简单的 i18n (国际化 (Internationalization) 的缩写) 插件
export default {
install: (app, options) => {
// 注入一个全局可用的 $translate() 方法
app.config.globalProperties.$translate = (key) => {
// 获取 `options` 对象的深层属性
// 使用 `key` 作为索引
return key.split('.').reduce((o, i) => {
if (o) return o[i]
}, options)
}
}
}
一个自己的 UI 库
- 声明一个
MyUI
import { Button, ButtonGroup } from './components/button';
import { Input } from './components/input';
import { Select, Option, SelectButton } from './components/select';
const prefixer = 'My';
const components = {
Button,
ButtonGroup,
Input,
Select,
Option,
SelectButton
};
export default {
install(app, options) {
for (let k in components) {
const Comp = components[k];
app.component(`${prefixer}${k}`, Comp);
}
}
};
- 在
main.js中使用
import { createApp } from 'vue';
import MyUI from 'my-ui';
import App from './App.vue';
const app = createApp(App);
app.use(MyUI);
app.mount('#app');
插件中的 provide & inject
以 i18n 为例:
- app.provide
export default {
install(app, options) {
app.provide('i18n', options);
}
};
- app.inject
import { defineComponent } from 'vue';
export default defineComponent({
name: 'Comp',
inject: ['i18n'],
});