[Vue @Component] Extend Vue Components in TypeScript

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Vue @Component] Extend Vue Components in TypeScript相关的知识,希望对你有一定的参考价值。

This lesson shows how you can extend and reuse logic in Vue components using TypeScript inheritance. It will take you through extending a component, its properties and methods, and how hooks are triggered along the inheritance tree.

 

We can define a Parent.ts file, which only contains the logic without any template:

import { Component, Vue } from ‘vue-property-decorator‘;

@Component
export default class Parent extends Vue {
    created() {
        console.log("Parent is created")
    }

    click() {
        console.log("Parent is clicked")
    }

    parentClicked() {
        console.log("Parent is clicked")
    }
}

 

Then we can extends this Parent Class from a vue component:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <h2>{{ fullMessage }}</h2>
    <button @click="click">Click</button>
    <button @click="parentClicked">Parent Click</button>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from ‘vue-property-decorator‘;
import Parent from ‘./Parent‘;

@Component
export default class HelloWorld extends Parent {
  @Prop() private msg!: string;

  // replace computed props
  get fullMessage() {
    return `${this.msg} should be fullmessage from a getter`
  }

  created() {
    console.log("Component is created")
  }

  click() {
    alert(‘Should replace what used to be defined in methods objects‘)
  }
}
</script>

 

Once we extends from Parent, HelloWorld Component can inherit its Parent class‘s methods and props.

 For example:

Will call parentClicked method from Parent Class from HelloWorld Component.

<!-- HelloWorld.vue -->
<button @click="parentClicked">Parent Click</button>

 

If we don‘t define ‘click‘ method in HelloWolrd component, it will using Parent‘s click() method.

以上是关于[Vue @Component] Extend Vue Components in TypeScript的主要内容,如果未能解决你的问题,请参考以下文章

vue.extend、 new vue()、component、render

new Vue/Vue.Component/Vue.extend的区别

Vue.mixin Vue.extend(Vue.component)的原理与区别

[Vue @Component] Extend Vue Components in TypeScript

vue19 组建 Vue.extend component

Vue.extend与Vue.component的区别