纵有疾风起
人生不言弃

vue组件 组件的继承extend

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/m0_37068028/article/details/79827132


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的好处是,使用一个拥有多个配置项的组件,通过继承,将不常用到的参数设置默认

未经允许不得转载:起风网 » vue组件 组件的继承extend
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录