什么是vuejs plugin插件
vuejs plugin插件是一個向你的app注入新的全局功能的強大但又簡約的方式。從概念上來說,vue plugin非常簡單,它就是一個包含了install方法的object.而這個install方法有兩個參數會傳入,第一個參數為全局的Vue構造函數,第二個參數則是options對象.
你的首個插件(任何組件mounted就自動打印mounted log日志)
我們先寫一個簡單的vue plugin,實現的功能是每個component,當mounted時就能夠打印相應的已加載信息
// This is your plugin object. It can be exported to be used anywhere. const MyPlugin = { // The install method is all that needs to exist on the plugin object. // It takes the global Vue object as well as user-defined options. install(Vue, options) { // We call Vue.mixin() here to inject functionality into all components. Vue.mixin({ // Anything added to a mixin will be injected into all components. // In this case, the mounted() method runs when the component is added to the DOM. mounted() { console.log('Mounted!'); } }); } }; export default MyPlugin;
這個插件本質上做的工作就是通過調用Vue.mixin向Vue全局構造函數中添加相應的mounted hook
隨后,我們通過vue.use來調用這個plugin
import Vue from 'vue' import MyPlugin from './my-vue-plugin.js' import App from './App.vue' // The plugin is loaded here. Vue.use(MyPlugin) new Vue({ el: '#app', render: h => h(App) });
需要注意的是:所有的plugin都必須在調用new Vue()之前被Vue.use來初始化
你可能在疑惑,為什么我不能直接在main.js中調用Vue.mixin()來實現同樣的功能呢?很重要的原因是因為我們是向Vue添加全局的functionality,而不是在向app添加功能。
添加其他的功能(installing app-wide components and directives)
比如,如果希望通過plugin方式來打包並且分發components以及directives的話,可以寫以下代碼:
import MyComponent from './components/MyComponent.vue'; import MyDirective from './directives/MyDirective.js'; const MyPlugin { install(Vue, options) { Vue.component(MyComponent.name, MyComponent) Vue.directive(MyDirective.name, MyDirective) } }; export default MyPlugin;
修改全局的Vue構造函數對象
看下面的代碼:
const MyPlugin { install(Vue, options) { Vue.myAddedProperty = 'Example Property' Vue.myAddedMethod = function() { return Vue.myAddedProperty } } }; export default MyPlugin;
修改Vue實例化instance
通過javascript的原型機制我們知道所有的vue component都是Vue構造函數new出來的instance,我們只要修改構造函數的prototype就能對instance統一添加新的功能。
const MyPlugin { install(Vue, options) { Vue.prototype.$myAddedProperty = 'Example Property' Vue.prototype.$myAddedMethod = function() { return this.$myAddedProperty } } }; export default MyPlugin;
上面添加的所有屬性或者方法都將在vue component instance中能夠通過this.$myAddedProperty來訪問.
添加組件的lifecycle hooks或者屬性
const MyPlugin = { install(Vue, options) { Vue.mixin({ mounted() { console.log('Mounted!'); } }); } }; export default MyPlugin;
自動安裝
對於那些沒有使用webpack等模塊打包工具的開發者來說,他們往往會將yourplugin.js放在vuejs的script tag之后來引用,可以通過在my-vue-plugin.js中的以下代碼來自動安裝
// Automatic installation if Vue has been added to the global scope. if (typeof window !== 'undefined' && window.Vue) { window.Vue.use(MyPlugin) }