Mixins are a very flexible way to distribute reusable functionality in Vue components. A mixed object can contain any component option. When a mixed object is used with a component, all the options for the mixed object are mixed in with the component’s own options. Personal: Mixin is used to extract and encapsulate the common parts of a VUE component, including data objects, hook functions, methods, and other options, so that code can be reused. Mixin is quite useful, but let’s see how it is used in practice.

Basic usage

// This is used in the main.js root file, as well as in groups import Vue from 'Vue '; Var mixin = {data() {return {name: 'www.vipbic.com', author: 'author'}}, created: Function () {console.log('Website: '+ this.name)}, methods: {foo: Function () {console.log(' author: '+ this.author)}, conflicting: function() { console.log('from mixin') } } } new Vue({ mixins: [mixin], render: H => h(App), created() {let option = this.$options.donotinit console.log('option: ',); This.foo ()}}).$mount('#app') var mixin = {data() {return {name: }}, created: function() {console.log('Website: '+ this.name)}, methods: {foo: Function () {console.log(' author: '+ this.author)}}} export default {mixins: [mixin], created(){ this.foo() } } </script>Copy the code

The effect is as follows, all the same, and you can see that created in mixed mixins has a higher priority than the component created execution

Global registration

Main.js

import Vue from 'vue';
var mixin = {
    data() {
        return {
            name: 'www.vipbic.com'.author: 'Mr. Sheep'}},created: function() {
        console.log('Website: + this.name)
    },
    methods: {
        foo: function() {
            console.log('Author:' + this.author)
        }
    }
}

Vue.mixin(mixin)
new Vue({
    render: h= > h(App)
}).$mount('#app')
Copy the code

So here’s what happens, let’s not call it, let’s see if the console prints anything, and you can see that we didn’t call it, we printed it twice, and as you normally think about it you might think that executing it once, which is normal, initializing it once, but executing it twice

How to solve the problem of executing twice

I’ve seen it done on the Internet, and it’s all from the official website, but I haven’t seen it on the official website, but it does solve the problem

var mixin = {
    data() {
        return {
            name: 'www.vipbic.com'.author: 'Mr. Sheep'}},created: function() {
        let option = this.$options.doNotInit;
        console.log(option) // Execute true the first time and undefined the second time
        if(! option) {// You can put some of your logic, such as the method to be called in the first place
            console.log('Website: + this.name)
        }
    },
    methods: {
        foo: function() {
            console.log('Author:' + this.author)
        },
    }
}

Vue.mixin(mixin);
new Vue({
    doNotInit: true.// Add a state
    render: h= > h(App),
}).$mount('#app')
Copy the code

Results the following

How to call

Did you just explain how to solve the problem of calling twice

// main.js import Vue from 'vue'; Var mixin = {data() {return {name: 'www.vipbic.com', author: 'author'}}, created: function() { let option = this.$options.doNotInit; if (! Option) {console.log('Website: '+ this.name)}}, methods: {foo: Function () {console.log(' author: '+ this.author)},}} vue.mixin (mixin); new Vue({ doNotInit: true, render: H = > h (App),}). $mount (' # App ') / / component invokes the < script > export default {created () {enclosing foo ()},} < / script >Copy the code

Modular registration

Create a separate mixin.js file

import Vue from 'vue';
var mixin = {
    data() {
        return {
            name: 'www.vipbic.com'.author: 'Mr. Sheep'}},created: function() {
        let option = this.$options.doNotInit;
        if(! option) {console.log('Website: + this.name)
        }
    },
    methods: {
        foo: function() {
            console.log('Author:' + this.author)
        },
        conflicting: function() {
            console.log('from mixin')}}}export default {
    install(Vue) {
        Vue.mixin(mixin)
    }
}
Copy the code
// Register with use in main.js
Vue.use(myMixin);
new Vue({
    doNotInit: true.render: h= > h(App),
}).$mount('#app')
Copy the code
<script> export default {created(){this.foo()},} </script>Copy the code

The effect is the same as main.js registration

Developing a plug-in

Use (VueRouter); Vue. Js (VueRouter); use(VueRouter); The first argument to this method is the Vue constructor, and the second argument is an optional option object. Plug-ins typically add global functionality to Vue. There is no limit to the scope of plug-ins — there are generally the following:

Add global resources: directives/filters/transitions, etc., such as Vue-touch. Add component options via global mixin methods. Vuex 4, add Vue instance methods by adding them to vue.prototype. 5. A library that provides its own API and one or more of the functions mentioned above, such as Vue-RouterCopy the code
let MyPlugin = {}
MyPlugin.install = function (Vue, options) {
  // 1. Add global methods or properties
   Vue.prototype.$myMethod = function (options) {
    / / logic...
  }

  // 2. Add the global resource directive
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      / / logic...}})// 3. Inject components, as mentioned above,vue is very flexible depending on how you dig it
  Vue.mixin({
    created: function () {
      / / logic...}})}Copy the code

Add global methods or properties

import Vue from 'vue';
// The first parameter is passed as an instance of Vue, and the second parameter is an optional option object
MyPlugin.install = function(Vue, options) {
    console.log(options) // Print the parameters
    Vue.prototype.myName = options.name
    Vue.prototype.myAuthor = function() {
        return options.author
    }
}
Vue.use(MyPlugin, {
    name: 'www.vipbic.com' // Pass parameters
    author: 'Mr. Sheep'
});

new Vue({
    render: h= > h(App),
}).$mount('#app')
Copy the code

Called in a component

<script>
export default {
    created(){
        console.log(this.myName)
        console.log(this.myAuthor())
    },
}
</script>
Copy the code

Results the following

Adding global Resources

// The vue directive can be added globally as well as within the component
import Vue from 'vue';
let MyPlugin = {}
MyPlugin.install = function(Vue, options) {
    Vue.directive("hello", {
        bind: function(el, bingind, vnode) {
            console.log(options)
            el.style["color"] = bingind.value;
            console.log("1-bind");
        },
        inserted: function() {
            console.log("2-insert");
        },
        update: function() {
            console.log("3-update");
        },
        componentUpdated: function() {
            console.log('4 - componentUpdated');
        },
        unbind: function() {
            console.log('5 - unbind'); }})}// Pass parameters
Vue.use(MyPlugin, {
    name: 'www.vipbic.com'.author: 'Mr. Sheep'
});
new Vue({
    render: h= > h(App),
}).$mount('#app')
Copy the code

Used in groups

<template> <div> <span v-hello="color3">{{message}}</span> < button@click ="add"> </button> <button </div> </template> <script> export default {data(){return {message:10, color3:"red" } }, methods:{ add(){ this.message++; }, jiebang(){ this.$destroy(); < span style ="less" scoped> </style>Copy the code

Effect of the page

Directive (directive) : directive (directive) : directive (Directive) : Directive

Name: the name of the directive without the v-prefix value: the binding value of the directive. For example, the value in the example above is red oldValue: The previous value of the directive binding, available only in update and componentUpdated hooks. Expression: a string of instruction expressions. Arg: An optional argument passed to the instruction. Modifiers: An object that contains modifiersCopy the code

Custom instructions have five life cycles (also called hook functions) :

bind, inserted, update, componentUpdate, unbind
Copy the code
// In the example aboveBind is called only once, when the directive is first bound to an element. This hook allows you to define an initialization action to be performed once on the binding. Inserted: called when the bound element is inserted into the parent node (called only when the parent node exists, not necessarilydocumentUpdate (componentUpdate (componentUpdate (componentUpdate (componentUpdate (componentUpdate (componentUpdate (componentUpdate)); It's called only once, when the directive month element is unbundledCopy the code

In the yellow box of the picture, the data is initialized after the component uses the V-Hello instruction, and the accept parameter is printed. After clicking unbind, adding 1 to start is invalid

Injection components

let MyPlugin = {}
MyPlugin.install = function(Vue, options) {
    Vue.mixin({
        data() {
            return {
                name: options.name
            }
        },
        methods: {
            getUser() {
                return options.author
            }
        }
    })
}
Vue.use(MyPlugin, {
    name: 'www.vipbic.com'.author: 'Mr. Sheep'
})
new Vue({
    render: h= > h(App),
}).$mount('#app')
Copy the code

Used in components

export default {
    data(){
        return {
      		
        }
    },
    created(){
 	// Where name and getUser are from global injection
        console.log(this.name)
        console.log(this.getUser())
    }
}
Copy the code

The effect

Use automatically prevents the same plug-in from being registered more than once

See article

Web front-end development – mixed vue. directive directive

About me