Vue Class Component

7.2.6 · maintenance · verified Sun Apr 19

Vue Class Component provides ES201X/TypeScript class decorators that allow developers to write Vue components using a class-based syntax, leveraging features like decorators, inheritance, and strong typing. The current stable version, 7.2.6, is designed for Vue 2.x projects. While Vue 3 primarily uses the Composition API, this library offered a structured approach for large Vue 2 applications, particularly for those coming from object-oriented backgrounds or using TypeScript extensively. The project has moved towards a 'maintenance' state for the Vue 2 compatible version, with active development on a beta version (v8) targeting Vue 3. Release cadence for v7.x has been irregular, with bug fixes and minor improvements. Its key differentiator is simplifying component definition and lifecycle management with TypeScript classes, providing a more organized code structure compared to the Options API for complex components.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a basic Vue 2 component using vue-class-component, including data, props, computed properties, methods, and a lifecycle hook.

import Vue from 'vue'
import Component from 'vue-class-component'

interface MyData {
  message: string
  count: number
}

@Component({
  props: {
    propMessage: String
  }
})
export default class MyComponent extends Vue {
  // Initial data
  message: string = 'Hello from Vue Class Component!'
  count: number = 0

  // Declared props
  readonly propMessage!: string

  // Computed property
  get reversedMessage(): string {
    return this.message.split('').reverse().join('')
  }

  // Method
  increment(): void {
    this.count++
  }

  // Lifecycle hook
  mounted(): void {
    console.log('Component mounted with prop:', this.propMessage)
    console.log('Initial message:', this.message)
  }

  // Template rendered implicitly or via a render function
  render(h: Function) {
    return h('div', [
      h('h2', this.message),
      h('p', `Prop message: ${this.propMessage}`),
      h('p', `Count: ${this.count}`),
      h('p', `Reversed: ${this.reversedMessage}`),
      h('button', { on: { click: this.increment } }, 'Increment')
    ])
  }
}

// To use this component
// new Vue({
//   el: '#app',
//   render: h => h(MyComponent, { props: { propMessage: 'A prop value!' } })
// })

view raw JSON →