vue-mixins

1.當組件使用混入對象時,全部混入對象的選項將被混入該組件自己的選項。

例子:數組

// 定義一個混入對象
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!"

2.當組件和混入對象含有同名選項時,這些選項將以恰當的方式混合。

好比,數據對象在內部會進行遞歸合併,在和組件的數據發生衝突時以組件數據優先。函數

var mixin = {
  data: function () {
    return {
      message: 'hello',
      foo: 'abc'
    }
  }
}

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

3.同名鉤子函數將混合爲一個數組,所以都將被調用。另外,混入對象的鉤子將在組件自身鉤子以前調用。

var mixin = {
  created: function () {
    console.log('混入對象的鉤子被調用')
  }
}

new Vue({
  mixins: [mixin],
  created: function () {
    console.log('組件鉤子被調用')
  }
})

// => "混入對象的鉤子被調用"
// => "組件鉤子被調用"

4.值爲對象的選項,例如 methodscomponents 和 directives,將被混合爲同一個對象。兩個對象鍵名衝突時,取組件對象的鍵值對。

var mixin = {
  methods: {
    foo: function () {
      console.log('foo')
    },
    conflicting: function () {
      console.log('from mixin')
    }
  }
}

var vm = new Vue({
  mixins: [mixin],
  methods: {
    bar: function () {
      console.log('bar')
    },
    conflicting: function () {
      console.log('from self')
    }
  }
})

vm.foo() // => "foo"
vm.bar() // => "bar"
vm.conflicting() // => "from self"
本站公眾號
   歡迎關注本站公眾號,獲取更多信息