vue组件 组件的继承

import Vue from 'vue'
const component = {
  data () {
    return {
      text: 111
    }
  },
  props: {
    propOne: String
  },
  mounted () {
    console.log('component1 mounted')
  },
  template: `<div>
    <div>component1 {{text}}</div>
    <div>{{propOne}}</div>
  </div>`
}
1. 继承的方式1, 使用Vue.extend()

传递props,不能直接使用props,需要用propsData

const CompVue = Vue.extend(component)

new CompVue({
  el: '#root',
  data () {
    return {
      text: 999
    }
  },
  propsData: { 不能直接使用props
    propOne: 'aaa'
  }

2. 继承的方式2, 使用extends 定义

const component2 = {
  extends: component,
  data () {
    return {
      text: 222
    }
  },
  mounted () {
    console.log('component2 mounted')
    console.log(this.$parent.$options.name) // Root
    this.$parent.text = 12345
  }
}

new Vue({
  name: 'Root',
  el: '#root',
  data () {
    return {
      text: 333
    }
  },
  components: {
    Comp: component2
  },
  template: `
    <div>
    <div>root {{text}}</div>
    <comp></comp>
    </div>
  `
})
继承的子组件通过this.$parent可以更改父组件的data,不推荐直接修改父组件的内容 
使用extend的好处是,使用一个拥有多个配置项的组件,通过继承,将不常用到的参数设置默认
--------------------- 
作者:虚年 
来源:CSDN 
原文:https://blog.csdn.net/m0_37068028/article/details/79827132 
版权声明:本文为博主原创文章,转载请附上博文链接!

Logo

前往低代码交流专区

更多推荐