创建你自己定制的vuejs plugin扩展app的功能

什么是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)
}
原文地址:https://www.cnblogs.com/kidsitcn/p/11150914.html