[Frontend筆記] 在Vue自製plugin!

總結了在Vue2.x和Vue3中各自如何自製plugin

Posted by 李定宇 on Thursday, March 17, 2022

Vue 中自製 plugin

在 Vue2.x 中自製 plugin

添加全局方法

(pluginDemo.js)

export default {
	 install(Vue) {
	 	  Vue.myGlobalMethod = function (...args) {
	 	  		//...todo
	 	  }
	 }
}

新增自訂指令(v-my-directive

(pluginDemo.js)

export default {
	 install(Vue) {
			 	 Vue.directive('my-directive', { bind (el, binding, vnode, oldVnode) {
			 	 	//... todo
			 	 }
		  });
	 }
}

新增 mixin

(pluginDemo.js)

export default{
	install(Vue){
		Vue.misin({
			created:function(){
				//...todo
			},
			methods:{
				demoFunc(){
				//...todo
				}
			}
		})
	}
}

啟用組件

(pluginDemo.js)

export default {
	 install(Vue) {
	 		Vue.component('my-component', MyComponent);
	 }
}

於 Vue 原型添加屬性

(pluginDemo.js)

export default {
	 install(Vue) {
	 		 Vue.prototype.$myMethod = function (methodOptions) {
	 		 	//...todo
	 		 }
   	 }
}

註冊 plugin,在main.js

import Vue from "vue";
import pluginDemo from "@/plugins/pluginDemo";

Vue.use(pluginDemo, { demoOptions : options });

在 Vue3 + Typescript.js 中自製 plugin

添加全局方法

(pluginDemo.ts)

import { App, Plugin, provide } from 'vue';
import IData from "./type.ts'

function demoGlobalFunc(){
	//... todo
}

export const pluginDemo: Plugin = {
    install: (app: App, options: IData) => {
    	app.provide('demoGlobalFunc', demoGlobalFunc)
    }
};

(Demo.vue)

import {defineComponent, inject} from 'vue'

export default defineComponent({
	setup(){
		const demoFunc = inject("demoGlobalFunc");
	}
})

新增自訂指令 (v-demo)

(pluginDemo.ts)

import { App, Plugin, provide } from 'vue';
import IData from "./type.ts'

export const pluginDemo: Plugin = {
    install: (app: App, options: IData) => {
    	app.directive('demo', {
    	   beforeMount(el: VueElement, binding: DirectiveBinding) {
    	   		 //...todo
    	   }
       	})
    }
};

新增 mixin,可以直接用 hook 來做

啟用組件

(pluginDemo.ts)

import { App, Plugin } from 'vue';
import MyComponent from '@/components/MyComponents.vue"
import IData from "./type.ts'

export const pluginDemo: Plugin = {
    install: (app: App, options: IData) => {
    	app.component('my-component', MyComponent)
    }
};

於 Vue 原型添加屬性

(pluginDemo.ts)

import { App, Plugin } from 'vue';
import IData from "./type.ts'

export const pluginDemo: Plugin = {
    install: (app: App, options: IData) => {
        app.config.globalProperties.$myMethod = (arg: any) => {
        		//...
        }
    }
};

要使用的時候(假設在 Demo.vue中)

import {defineComponent, getCurrentInstance} from 'vue'

export default defineComponent({
	setup{
		const { appContext } = getCurrentInstance()
		appContext.config.globalProperties.$myMethod(...)
	}
})