4.1 Mixins 混入
1. 什么是Mixins
当多个组件内部都写了同样的方法,如何将该方法提取出来,减少代码量呢?
Vue实现方式如下:
// define a mixin object
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // => "hello from mixin!"
2. mixins里定义的和组件内部定义的重复冲突了怎么办
2.1 数据对象是采取合并策略,
组件内部的覆盖mixins里定义的,如下:
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" }
}
})
2.2 钩子函数采取的是将他们merge进数组
都触发,先触发mixins中的函数,如下
var mixin = {
created: function () {
console.log('mixin hook called')
}
}
new Vue({
mixins: [mixin],
created: function () {
console.log('component hook called')
}
})
// => "mixin hook called"
// => "component hook called"
3. 其他
另外你也可以定义全局混入,即每创建一个vue对象,都会merge全局定义的mixins中的对象,慎用
vue提供了api,让你甚至可以自定义合并的策略
(完)
【更多Vue文档解读】:《Vue Doc 笔记》