The plug-in

All systems that can extend Vue are called plug-ins.

When a written component adds install, it can be called as a plug-in with vue.use ()

// Component definition
class MyPlugin{}
// Plug-in definition
MyPlugin.install = function (Vue, options) {
    Vue.prototype.$myPlugin = new MyPlugin()
}
// Plugins are used
Vue.use(MyPlugin)
Copy the code

1. Add global methods or properties

Mount it statically

// 1. Add global methods or attributes
  Vue.myGlobalMethod = function () {
	/ / logic...}}Copy the code

2. Create global directives and filters

// 2. Add global resources
Vue.directive('my-directive', {
  bind(el, binding, vnode, oldVnode) {
  	/ / logic...}... })Copy the code

3. With

Purpose: Distribute reusable flexible functionality of Vue components

Mixin constructor, that is, global mixin applies to all components, extending Vue

// 3. Inject component options
Vue.mixin({
  created: function () {
  	/ / logic... Is merged with component created}... })Copy the code

With global

// Global mixin 👇
Vue.mixin({
    beforeCreate(){
        // Will be entered when all components are initialized for extension
        // Currently this is a Vue component instance
        if(this.$options.router){
            // You only want to execute once on the root component
            this.$options.router.init()
        }
    }
})
Copy the code

The component with

// Components are mixed in 👇
// Define a mixin object
var myMixin = {
    created: function () {
    	this.hello()
    },
    methods: {
    	hello: function () {
    		console.log('hello from mixin! ')}}}// The component to use
import mixin from 'mixin'
mixin: ['myMixin']
// the method is used
this.hello()
Copy the code

4. Add an instance

// 4
Vue.prototype.$myMethod = function (methodOptions) {
	/ / logic...
}
Copy the code

[Duo Duo debut]