在vue2的插件那篇文章我们介绍过插件其实就是vue的增强功能。通常来为vue添加全局功能的。在vue3中插件的功能也是一样的,只是它们在定义上有所不同。
一个插件可以是一个拥有 install() 方法的对象,也可以直接是一个安装函数本身。安装函数会接收到安装它的应用实例和传递给 app.use() 的额外选项作为参数:
下面是我定义的一个插件,为了方便管理,在src目录下新建一个plugins文件夹,根据插件的功能,文件夹里面可以放置很多js文件。
export default {
install: (app, options) => {
// 注入一个全局可用的方法
app.config.globalProperties.$myMethod = () => {
console.log("这是插件的全局方法");
}
// 添加全局指令
app.directive("my-directive", {
bind (el, binding, vnode, oldVnode) {
console.log("这是插件的全局指令");
}
})
}
}
我们一般是安装在全局的,这样方便多个组件使用。
// main.js
import { createApp } from "vue"
import App from "./App.vue"
import ElementPlus from "element-plus"
import "element-plus/dist/index.css"
import myPlugin from "./plugins/myPlugin"
createApp(App).use(ElementPlus).use(myPlugin).mount("#app");
在组件中使用
<template>
<div v-my-directive></div>
<el-button @click="clicFunc">测试按钮</el-button>
</template>
<script setup>
import { getCurrentInstance } from "vue";
const ctx = getCurrentInstance();
console.log("ctx", ctx);
const clicFunc = ctx.appContext.app.config.globalProperties.$myMethod();
</script>
效果如下:

在插件中,还可以通过provide为插件用户提供一些内容,比如像下面这样,将options参数再传给插件用户,也就是组件中。
// myPlugin.js
export default {
install: (app, options) => {
// 注入一个全局可用的方法
app.config.globalProperties.$myMethod = () => {
console.log("这是插件的全局方法");
}
// 添加全局指令
app.directive("my-directive", {
bind () {
console.log("这是插件的全局指令");
}
})
// 将options传给插件用户
app.provide("options", options);
}
}
// main.js
import { createApp } from "vue"
import App from "./App.vue"
import ElementPlus from "element-plus"
import "element-plus/dist/index.css"
import myPlugin from "./plugins/myPlugin"
createApp(App).use(ElementPlus).use(myPlugin, {
hello: "你好呀"
}).mount("#app");
// 组件中使用
<template>
<div v-my-directive></div>
<el-button @click="clicFunc">测试按钮</el-button>
</template>
<script setup>
import { getCurrentInstance, inject } from "vue";
const ctx = getCurrentInstance();
const hello = inject("options");
console.log("hello", hello);
const clicFunc = ctx.appContext.app.config.globalProperties.$myMethod();
</script>
效果如下:

以上就是vue3自定义插件的作用场景及使用示例详解的详细内容,更多关于vue3自定义插件作用的资料请关注其它相关文章!
