插件一般會爲 Vue 添加全局功能。插件的範圍沒有限制——通常有下面幾種:
1.添加全局方法或者屬性,如: vue-custom-element
2.添加全局資源:指令/過濾器/過渡等,如 vue-touch
3.經過全局 mixin 方法添加一些組件選項,如: vue-router
4.添加 Vue 實例方法,經過把它們添加到 Vue.prototype 上實現。
5.一個庫,提供本身的 API,同時提供上面提到的一個或多個功能,如 vue-routervue
Vue.js 的插件應當有一個公開方法 install 。這個方法的第一個參數是 Vue 構造器,第二個參數是一個可選的選項對象:node
MyPlugin.install = function (Vue, options) { // 1. 添加全局方法或屬性 Vue.myGlobalMethod = function () { // 邏輯... } // 2. 添加全局自定義指令 Vue.directive('my-directive', { bind (el, binding, vnode, oldVnode) { // 邏輯... } ... }) // 3. 添加全局mixin Vue.mixin({ created: function () { // 邏輯... } ... }) // 4. 添加實例方法 Vue.prototype.$myMethod = function (methodOptions) { // 邏輯... } }
toast.vue
<template> <div class="my-toast" v-show="show">{{text}}</div> </template> <script> export default { data(){ return { text: '', show: true }; } }; </script>
toast.js
import Vue from 'vue'; import toastComponent from './toast.vue'; const ToastConstruction = Vue.extend(toastComponent); // 建立Vue子類 function showToast (text, duration = 2000) { const toast = new ToastConstruction(); let el = toast.$mount().$el; // 掛載實例,獲取實例DOM元素 document.body.appendChild(el); // 將toast實例DOM元素添加到文檔中 setTimeout(() => { document.body.removeChild(el); }, duration); } function registryToast() { // 添加實例方法 Vue.prototype.$toast = showToast; // 添加全局方法 Vue.$toast = showToast; // 添加全局mixin Vue.mixin({ methods: { toast: showToast } }); // 添加全局指令 Vue.directive('show-toast', { bind(el, binding, vnode){ el.addEventListener('click', function (e) { showToast(binding.value); }); } }); } export default registryToast;
這樣,一個簡單的toast插件就作好了!vue-router
全局入口文件 main.js
app
... import Vue from 'vue'; import myToast from './plugin/toast'; Vue.use(myToast); // 至關於調用插件的 install 方法(若是插件是一個對象,必須提供 install 方法。若是插件是一個函數,它會被做爲 install 方法。install 方法調用時,會將 Vue 做爲參數傳入。) ...
須要調用toast的頁面 page/page.vue
函數
<template> ... <p @click="testGlobal">全局方法</p> <p @click="testPrototype">實例方法</p> <p @click="testMixin">mixin</p> <p v-show-toast="'指令'">指令</p> // 使用指令觸發 ... </template> <script> import Vue from 'vue'; ... methods: { testGlobal(){ Vue.$toast('Global'); // 全局方法 }, testMixin(){ this.toast('Mixin'); // 利用mixin注入方法 }, testPrototype(){ this.$toast('Prototype'); // 利用prototype添加實例方法 } } ... </script>