Vue:混入的使用和作用

最近在跟着Vue.js教程自学Vue,看到混入这一章的时候感觉没能理解它的作用。看了一下混入的定义:

混入是一种分发Vue组件中可复用功能非常灵活的方式。混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被混入该组件本身的选项。

例子:

//定义一个混入对象
var myMixin={
    created:function(){
        this.hello();
    },
    methods:{
        hello:function(){
            console.log('hello from mixin');
        }
    }
}
//定义一个使用混入对象的组件
var Component = Vue.extend({
    mixins:[myMixin]
})
var component = new Component();           

结果:hello from mixin  
// 这里混入对象的hello()这个方法可以在组件中被直接调用

当组件和混入对象含有同名选项时,这些选项将以恰当的方式混合:

var mixin ={
    data:function(){
        return{
            messageL:'hello',
            foo:'abc'
        }
    },
    created(){
        console.log('混入对象的钩子被调用')
    }
}

new Vue({
    mixins:[mixin],
    data:function(){
        return{
            message:'goodbye',
            bar:'def
        }
    },
    created:function(){
        console.log('组件钩子被调用')
        console.log(this.$data);
        // => { message: "goodbye", foo: "abc", bar: "def" }
    }
  })

Guess you like

Origin blog.csdn.net/qq_36451496/article/details/100665989