Vue3 入门教程
插件
本教程共 40 篇 · 第 31 篇 · 更新于 2026-07-29 · 约 6 分钟阅读
VueVue3 入门教程Plugins插件app.useinstall
31. 插件
本节目标:搞清楚插件是什么,怎么安装,怎么自己写一个。
插件是什么
插件是给 Vue 应用添加全局功能的独立代码单元。你可以把它理解为给 Vue 应用”安装扩展”:
import { createApp } from 'vue'
const app = createApp({})
app.use(myPlugin, {
/* 可选配置 */
})
插件对象需要暴露一个 install 方法,或者直接是一个函数:
const myPlugin = {
install(app, options) {
// app 是 Vue 应用实例
// options 是 app.use() 传的第二个参数
}
}
插件能做什么
Vue 没有严格限制插件的用途,但常见场景有四种:
| 能力 | 方法 | 例子 |
|---|---|---|
| 注册全局组件 | app.component() | 全局按钮组件 |
| 注册全局指令 | app.directive() | v-focus 指令 |
| 提供全局注入 | app.provide() | 国际化函数 |
| 添加全局属性 | app.config.globalProperties | $translate 方法 |
写一个简单的 i18n 插件
我们来写一个极简版的国际化插件,让所有模板都能用 $translate 函数翻译字符串:
export default {
install: (app, options) => {
app.config.globalProperties.$translate = (key) => {
// 把 'greetings.hello' 拆成路径,逐层查找
return key.split('.').reduce((o, i) => {
if (o) return o[i]
}, options)
}
}
}
使用时传入翻译数据:
import i18nPlugin from './plugins/i18n.js'
app.use(i18nPlugin, {
greetings: {
hello: 'Bonjour!'
}
})
模板里直接用:
<h1>{{ $translate('greetings.hello') }}</h1>
Warning全局属性别滥用。项目里如果插件多了,你很容易忘记
$translate是哪个插件加的。适度就好。
用 provide/inject 传递数据
另一种方式是用 app.provide,让组件通过 inject 获取数据:
export default {
install: (app, options) => {
app.provide('i18n', options)
}
}
组件里用 inject 获取:
<script setup>
import { inject } from 'vue'
const i18n = inject('i18n')
console.log(i18n.greetings.hello)
</script>
对比一下两种方式:
| 方式 | 优点 | 缺点 |
|---|---|---|
globalProperties | 模板里直接用 $xxx | 容易冲突,不好追踪来源 |
provide/inject | 来源明确,不污染全局 | 每个组件都要 inject |
注册全局组件
如果你写了一个通用的组件库,可以通过插件一次性注册:
import MyButton from './components/MyButton.vue'
import MyInput from './components/MyInput.vue'
export default {
install(app) {
app.component('MyButton', MyButton)
app.component('MyInput', MyInput)
}
}
import MyUI from './plugins/my-ui.js'
app.use(MyUI)
之后所有组件都能直接用 <MyButton> 和 <MyInput>,不需要在每个组件里单独 import。
注册全局指令
同理,全局指令也可以用插件注册:
export default {
install(app) {
app.directive('focus', {
mounted(el) {
el.focus()
}
})
}
}
打包发布
如果想把插件发布到 npm 供他人使用,推荐用 Vite 的 Library Mode 打包。具体配置参考 Vite 官方文档。
本节回顾
- 插件通过
install(app, options)向 Vue 应用添加全局功能 - 可以做四件事:注册组件、注册指令、提供注入、添加全局属性
globalProperties简单但别滥用;provide/inject更干净- 常见 UI 库(如 Element Plus)就是通过插件注册全局组件的