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

main.js

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 
Vue.use(plugin);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

index.js

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 
  plugin.$mount(document.createElement("div"));

  //4、plugin.$el Corresponding to the above mounted div
  document.body.appendChild(plugin.$el);
  
  //5、 Definition Vue.$plugin Global access to 
  Vue.prototype.$plugin = plugin;
};

export default plugin; // take plugin export 

plugin.vue( Custom components )

<template>
  <div>
  </div>
</template>

<script>
export default {
  name: "Plugin",
}
</script>

<style scoped>
</style>

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

vue3 Method

difference

- 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

main.js

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

createApp(App).use(store).use(router).use(plugin).mount('#app');

index.js

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 
  document.body.appendChild(instance.$el);

  //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.
https://en.qdmana.com/2021/08/20210823192714602H.html

Random recommended