mixins和extends的区别
两个都可以理解为继承,mixins接收对象数组(可理解为多继承),extends接收的是对象或函数(可理解为单继承)。
1、继承钩子函数测试:
const extend = {
created () {
console.log('extends created')
}
}
const mixin1 = {
created () {
console.log('mixin1 created')
}
}
const mixin2 = {
created () {
console.log('mixin2 created')
}
}
export default {
extends: extend,
mixins: [mixin1, mixin2],
name: 'app',
created () {
console.log('created')
}
}
控制台输出:
extends created
mixin1 created
mixin2 created
created
- 结论: 优先调用mixins和extends继承的父类,extends触发的优先级更高,相对于是队列
- push(extend, mixin1, minxin2, 本身的钩子函数)
- 经过测试,watch的值继承规则一样。
2、继承methods测试
const extend = {
data () {
return {
name: 'extend name'
}
}
}
const mixin1 = {
data () {
return {
name: 'mixin1 name'
}
}
}
const mixin2 = {
data () {
return {
name: 'mixin2 name'
}
}
}
// name = 'name'
export default {
mixins: [mixin1, mixin2],
extends: extend,
name: 'app',
data () {
return {
name: 'name'
}
}
}
// 只写出子类,name = 'mixin2 name',extends会被mixins覆盖
export default {
extends: extend,
mixins: [mixin1, mixin2],
name: 'app'
}
// 只写出子类,name = 'mixin1 name',mixins后面继承会覆盖前面的
export default {
mixins: [mixin2, mixin1],
extends: extend,
name: 'app'
}
- 结论:子类再次声明,data中的变量都会被重写,以子类的为准。
- 如果子类不声明,data中的变量将会最后继承的父类为准。
- 经过测试,props中属性、methods中的方法和computed的值继承规则一样。