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: `
    
{{propOne}}
`
, 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: `
    
{{propOne}}
`
, 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: ``, mounted () { console.log('instance mounted') } }) 复制代码

使用场景

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

import Vue from 'vue'

const component = {
  props: {
    active: Boolean,
    propOne: String
  },
  template: `
    
{{propOne}}
`
, 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: `
{{text}}
`
, mounted () { console.log('instance mounted') } }) 复制代码

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

你可能感兴趣的:(Vue核心知识-Vue的组件之组件的继承)