混合mixins和extends

2018-11-06  本文已影响0人  前端girl吖

mixins(混入)用途:

extends用法:

相对于mixins,extends触发的优先级更高

两个均可以理解为继承,mixins接收对象数组(可理解为多继承),extends接收的是对象或函数(可理解为单继承)

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

结论:

继承的data和methods
const extend = {
 data () {
  return {
   name: 'extend name'
  }
 }
}
const mixin1 = {
 data () {
  return {
   name: 'mixin1 name'
  }
 }
}
const mixin2 = {
 data () {
  return {
   name: 'mixin2 name'
  }
 }
}

//1、子类再定义name属性
export default {
 mixins: [mixin1, mixin2],
 extends: extend,
 name: 'app',
 data () {
  return {
   name: 'name'
  }
 }
}
//结果 name="name"


//2、extends优先级高会被mixins覆盖,mixins后面继承会覆盖前面的
export default {
 mixins: [mixin1, mixin2],
 extends: extend,
 name: 'app'
}
//结果 name = 'mixin2 name'
结论:
ps:

extend
Vue.extend只是创建一个构造器,它是为了创建可复用的组件。其主要用来服务于Vue.component 用来生成组件

    <script>
        // 方式1:使用Vue.extend()创建组件构造器,然后使用Vue.component(标签名,组件构造器),根据组件构造器来创建组件 
        var MyComponent = Vue.extend({
            template: '<h2>custom-component1</h2>'
        });    
        Vue.component('custom-component1', MyComponent);      
       //方式2:直接创建组件(推荐)
        Vue.component('custom-component2', {
            template: '<h1>custom-component2</h1>'
        });        
    </script>
上一篇下一篇

猜你喜欢

热点阅读