Vue学习笔记 - 插件

介绍

插件 (Plugins) 是一种能为 Vue 添加全局功能的工具代码

1
2
3
4
5
6
7
import { createApp } from 'vue'

const app = createApp({})

app.use(myPlugin, {
/* 可选的选项 */
})

一个插件可以是一个拥有 install() 方法的对象,也可以直接是一个安装函数本身。安装函数会接收到安装它的应用实例和传递给 app.use() 的额外选项作为参数:

对象的写法

1
2
3
4
5
const myPlugin = {
install(app, options) {
// 配置此应用
}
}

函数的写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { App } from 'vue';
import HelloWorld from '@v3/components/HelloWorld.vue'
export default {
install(app: App, options) {
// 插件逻辑
console.log('MyPlugin is installed with options:', options);

// 你可以在这里添加全局方法、指令、混入等
// 示例:添加全局方法
app.config.globalProperties.$myMethod = () => {
return 'This is a method from MyPlugin!'
console.log('This is a method from MyPlugin!');
};
...
}
}

插件没有严格定义的使用范围,但是插件发挥作用的常见场景主要包括以下几种

  1. 通过 app.component()app.directive() 注册一到多个全局组件或自定义指令。
  2. 通过 app.provide() 使一个资源可被注入进整个应用。
  3. app.config.globalProperties 中添加一些全局实例属性或方法
  4. 一个可能上述三种都包含了的功能库 (例如 vue-router)。

编写一个插件

i18n (国际化 (Internationalization) 的缩写) 插件

创建插件代码文件

1
2
3
4
5
6
// plugins/i18n.js
export default {
install: (app, options) => {
// 在这里编写插件代码
}
}

有一个翻译函数,这个函数接收一个以 . 作为分隔符的 key 字符串,用来在用户提供的翻译字典中查找对应语言的文本

1
<h1>{{ $translate('greetings.hello') }}</h1>

这个函数应当能够在任意模板中被全局调用。这一点可以通过在插件中将它添加到 app.config.globalProperties 上来实现

1
2
3
4
5
6
7
8
9
10
11
12
13
// plugins/i18n.js
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)
}
}
}

$translate 函数会接收一个例如 greetings.hello 的字符串,在用户提供的翻译字典中查找,并返回翻译得到的值。

用于查找的翻译字典对象则应当在插件被安装时作为 app.use() 的额外参数被传入:

1
2
3
4
5
6
7
import i18nPlugin from './plugins/i18n'

app.use(i18nPlugin, {
greetings: {
hello: 'Bonjour!'
}
})

reduce 方法

reduce 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

01

先传greetings 返回对象{hello:'Bonjour'},再传hello,返回Bonjour,如果中间一个没有,就没有了

效果

一开始的表达式 $translate('greetings.hello') 就会在运行时被替换为 Bonjour 了。

插件中的 Provide / Inject

可以通过 provide 来为插件用户供给一些内容。举例来说,我们可以将插件接收到的 options 参数提供给整个应用,让任何组件都能使用这个翻译字典对象。

1
2
3
4
5
6
// plugins/i18n.js
export default {
install: (app, options) => {
app.provide('i18n', options)
}
}

想使用插件的开发者就可以在他们的组件中以 i18nkey 注入并访问插件的选项对象了

1
2
3
4
5
6
export default {
inject: ['i18n'],
created() {
console.log(this.i18n.greetings.hello)
}
}
  1. app.useoptions
  2. plugininstall
  3. pluginprovider
  4. 其它组件的 inject 接收并使用

参考

  1. Vue-插件
  2. vue3 + ts:开发插件 / Plugins / 注册全局实例 / 在 template 与 setup 中使用 / provide、inject
  3. JavaScript reduce() 方法
Vue 学习笔记 - 内置组件 - Transition Vue学习笔记 - 深入组件 - 注册,透传Attribute,异步组件
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×