vue中的混入

数据对象合并

数据对象在内部会进行浅合并 (一层属性深度),在和组件的数据发生冲突时以组件数据优先

var mixin = {
    data() {
        return {
            msg_mixins: 'mixins',
            msg: '123'
        }
    }
}
var app = new Vue({
    mixins: [mixin],
    el: '#app',
    data: {
        msg: 'app'
    }
})

钩子函数合并

同名钩子函数将混合为一个数组,因此都将被调用。另外,混入对象的钩子将在组件自身钩子之前调用。

var mixin = {
    data() {
        return {
            msg_mixins: 'mixins',
            msg: '123'
        }
    },
    created: function () {
        console.log('混入对象的钩子被调用')
    }
}
var app = new Vue({
    mixins: [mixin],
    el: '#app',
    data: {
        msg: 'app'
    },
    created: function () {
        console.log('组件钩子被调用')
    }
})

methods, components 和 directives合并

methods, components 和 directives,将被混合为同一个对象。两个对象键名冲突时,取组件对象的键值对。

var mixin = {
    data() {
        return {
            msg_mixins: 'mixins',
            msg: '123'
        }
    },
    created: function () {
        console.log('混入对象的钩子被调用')
    },
    methods: {
        foo: function () {
            console.log('foo')
        },
        conflicting: function () {
            console.log('from mixin')
        }
    }
}
var app = new Vue({
    mixins: [mixin],
    el: '#app',
    data: {
        msg: 'app'
    },
    created: function () {
        console.log('组件钩子被调用')
    },
    methods: {
        bar: function () {
            console.log('bar')
        },
        conflicting: function () {
            console.log('from self')
        }
    }
})

一下是vuerouter中使用混入的例子

 

const isDef = v => v !== undefined

Vue.mixin({
    beforeCreate () {
      if (isDef(this.$options.router)) {
        this._routerRoot = this
        this._router = this.$options.router
        this._router.init(this)
        Vue.util.defineReactive(this, '_route', this._router.history.current)
      } else {
        this._routerRoot = (this.$parent && this.$parent._routerRoot) || this
      }
      registerInstance(this, this)
    },
    destroyed () {
      registerInstance(this)
    }
  })

 

例子中表示只有存在router配置项的时候才进行操作,而在vuerouter使用的时候只有根组件下才配置router,这就表示只混入到根组件中,而不混入到其他组件中

 

转载于:https://www.cnblogs.com/wyongz/p/11435518.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值