Vue核心知识-Vue的组件之组件的继承

用法

Vue.extend( options )

参数:

{Object} options 用法:

使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。

data 选项是特例,需要注意 - 在 Vue.extend() 中它必须是函数

Vue实例使用 extend,属性的合并

下例中,

  • 通过 propsData 对 props 进行设置。
  • 设置 data 可直接对组件中的 data 进行覆盖
  • 组件内部的 mounted 先被调用,实例中的 mouted 后被调用。
import Vue from 'vue'

const component = {
  props: {
    active: Boolean,
    propOne: {
      required: true
    }
  },
  template: `
    <div>
      <input type="text" v-model="text"/>
      <span>{{propOne}}</span>
    </div>
  `,
  data () {
    return {
      text: 0
    }
  },
  mounted () {
    console.log('comp mounted')
  }
}

const CompVue = Vue.extend(component)

new CompVue({
  el: '#root',
  propsData: {
    propOne: 'xxx'
  },
  data: {
    text: '123'
  },
  mounted () {
    console.log('instance mounted')
  }
})
复制代码

组件内使用继承

component2 继承 component,再将 component2 在 vue 实例中注册使用。

观察 mounted 执行先后,发现控制台一次显示:

comp mounted

comp2 mounted

instance mounted

说明组件的执行顺序也是如此。

import Vue from 'vue'

const component = {
  props: {
    active: Boolean,
    propOne: String
  },
  template: `
    <div>
      <input type="text" v-model="text"/>
      <span>{{propOne}}</span>
    </div>
  `,
  data () {
    return {
      text: 0
    }
  },
  mounted () {
    console.log('comp mounted')
  }
}

const component2 = {
  extends: component, // 指定继承组件
  data () {
    return {
      text: 1
    }
  },
  mounted () {
    console.log('comp2 mounted')
  }
}

new Vue({
  el: '#root',
  components: {
    Comp: component2
  },
  template: `<comp></comp>`,
  mounted () {
    console.log('instance mounted')
  }
})
复制代码

使用场景

有一个功能完善的公用组件,当需要对组件进行扩展时,会用到 extend,而不需要重新写一个组件。

import Vue from 'vue'

const component = {
  props: {
    active: Boolean,
    propOne: String
  },
  template: `
    <div>
      <input type="text" v-model="text"/>
      <span>{{propOne}}</span>
    </div>
  `,
  data () {
    return {
      text: 0
    }
  },
  mounted () {
    console.log('comp mounted')
  }
}

const component2 = {
  extends: component, // 指定继承组件
  data () {
    return {
      text: 1
    }
  },
  mounted () {
    console.log(this.$parent.$options.name)
    this.$parent.text = '12345'
  }
}

new Vue({
  name: 'Root',
  el: '#root',
  components: {
    Comp: component2
  },
  data: {
    text: 23333
  },
  template: `
    <div>
      <span>{{text}}</span>
      <comp></comp>
    </div>
  `,
  mounted () {
    console.log('instance mounted')
  }
})
复制代码

转载于:https://juejin.im/post/5b92602cf265da0a8b57015d

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值