current position:Home>[vue3] encapsulate custom global plug-ins

[vue3] encapsulate custom global plug-ins

2021-08-23 19:27:16 kernel_ developer

【vue3】 Encapsulate custom global plug-ins

primary vue2 Method


import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import plugin from './···/plugin/index'

// Install custom plug-ins 

new Vue({
  render: h => h(App)


import Plugin from "./Plugin";

const plugin = {};

 * Vue:  stay main.js in Vue.use Automatically passed in when vue Instance as argument 
 *  	 At the same time, it will automatically execute install function 
plugin.install = function(Vue) {
  //1、 Create a component constructor 
  const pluginConstructor = Vue.extend(Plugin);

  //2、new The way , According to the component constructor , You can create a component object 
  const plugin = new pluginConstructor();

  //3、 The component object , Manually mount to an element 

  //4、plugin.$el Corresponding to the above mounted div
  //5、 Definition Vue.$plugin Global access to 
  Vue.prototype.$plugin = plugin;

export default plugin; // take plugin export 

plugin.vue( Custom components )


export default {
  name: "Plugin",

<style scoped>

vue3 And vue2 identical , Only the method of execution is different .

vue3 Method


- use(plugin) Automatically call install Function time 
 vue2:  Auto in Vue example 
 vue3:  Auto in App Application example 
-  Mount components 
 vue2: Vue.extend(plugin) +  Constructor instantiation  +  mount 
 vue3: createApp(plugin) +  mount 
-  Define global access 
 vue2: Vue.prototype.$plugin
 vue3: app.config.globalProperties.$plugin


import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import plugin from "···/plugin/index";



import Plugin from "./Plugin";
import {createApp} from 'vue'

const plugin = {};

plugin.install = function(app) {
  //1、 Instantiate and bind components 
  const plugin = createApp(Plugin);
  const instance = plugin.mount(document.createElement("div"));

  //2. To mount Node Add to body in 

  //3、 Define global 
  app.config.globalProperties.$plugin = instance;

export default plugin;

The whole idea is the same , so vue3 More encapsulation , Just less code .

copyright notice
author[kernel_ developer],Please bring the original link to reprint, thank you.

Random recommended