首页 > 文章列表 > vue3自定义插件的作用场景及使用方法是什么

vue3自定义插件的作用场景及使用方法是什么

Vue3
322 2023-05-19

vue3自定义插件的作用场景及使用方法是什么

插件的作用场景

在vue2的插件那篇文章我们介绍过插件其实就是vue的增强功能。通常来为vue添加全局功能的。在vue3中插件的功能也是一样的,只是它们在定义上有所不同。

  • 通过app.component()和app.directive()注册一到多个全局组件或自定义指令

  • 通过app.provide()使一个资源可被注入进整个应用

  • 向app.config.globalProperties中添加一些全局实例属性或方法

  • 一个可能上述三种都包含了的功能库(如vue-router)

插件的定义(注册)

一个插件可以是一个拥有 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/inject

在插件中,还可以通过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>

效果如下: