在实际的应用中,有不少的业务代码是能够重复使用的,vue.js自己是一个注重于高效率的框架,因此也提供了组件中的复用功能。混入 (mixins) 是一种分发 Vue组件中可复用功能的很是灵活的方式。混入对象能够包含任意组件选项。当组件使用混入对象时,全部混入对象的选项将被混入该组件自己的选项。以下:vue
// 定义一个混入对象
var mixinTest = {
created: function () {
this.mixinMethod()
},
methods: {
mixinMethod: function () {
console.log('mixinMethod from mixin!')
}
}
}
// 定义一个使用混入对象的组件
var Component = Vue.extend({
mixins: [mixinMethod]
})
var component = new Component() // => "hello from mixin!"
复制代码
从中能够发现当组件混入对象时,对象的方法以及钩子都被混入了该组件的自己。这种方式是很灵活的。那要是组件和混入对象含有同名选项时,也是有规则的,好比,当数据上和组件有同名时,以组件的数据为先。markdown
var mixin = {
data: function () {
return {
testA: 'aaaa',
testB: 'bbbb'
}
}
}
new Vue({
mixins: [mixin],
data: function () {
return {
testA: 'AAAA',
testC: 'CCCC'
}
},
created: function () {
console.log(this.$data)
// => { testA: "AAAA", testB: "bbbb", testC: "CCCC" }
}
})
复制代码
mixins对象里的testA和testB混入到了组件中的data中,同时出现了testA与组件同名,因此优先保留了组件的数据。框架
var mixin = {
created: function () {
console.log('混入对象的钩子')
}
}
new Vue({
mixins: [mixin],
created: function () {
console.log('组件的钩子')
}
})
// => "混入对象的钩子"
// => "组件的钩子"
复制代码
能够发现混入对象的钩子和组件的钩子都会执行,可是会先执行混入对象的钩子函数
var mixin = {
methods: {
mixinsMethod: function () {
console.log('mixinsMethod')
},
sameMethod: function () {
console.log('from mixin')
}
}
}
var vm = new Vue({
mixins: [mixin],
methods: {
selfMethod: function () {
console.log('selfMethod')
},
sameMethod: function () {
console.log('from self')
}
}
})
vm.mixinsMethod() // => "mixinsMethod"
vm.selfMethod() // => "selfMethod"
vm.sameMethod() // => "from self"
复制代码
由上可得,在值为对象的混入对象混入时,这些将和组件原有的选项混合一块儿成为一个对象,当对象的键名与组件的键名出现重复时,会使用组件的键名。工具
以上列举的都是单独的引入到某一个组件中使用。也能够全局注册混入对象。这样的话全部的实例就都会被混入的对象所做用。也能够根据本身须要作成一个具体的使用工具类。供全局全部的实例使用。不过也要当心使用,毕竟会影响到全部的组件,须要结合实际场景使用。this
Vue.mixin({
created: function () {
var option = this.$options.text
if (option) {
console.log(option)
}
}
})
new Vue({
text: 'globalMixins!'
})
// => "globalMixins!"
复制代码