zoukankan      html  css  js  c++  java
  • 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,这就表示只混入到根组件中,而不混入到其他组件中

  • 相关阅读:
    Unicode编码
    第2章 词法结构
    ubuntu thrift
    Django admin 忘记密码
    STL中的优先级队列priority_queue
    哈希表面试题-转载
    C++中基于成员函数是否是const重载成员函数
    printf格式输出知识整理
    Linux dns和网络连接配置方法
    Linux下高效并发服务器的常用方法和案例(转)
  • 原文地址:https://www.cnblogs.com/wyongz/p/11435518.html
Copyright © 2011-2022 走看看