Categories
JavaScript Vue

Create a Class Vue Compnent with vue-class-component

Spread the love

We can create a Vue component in a class-style component with the vue-class-component package.

To get started, we can use the Vue CLI to create a project with the ‘Manually select features’ option.

Then we select ‘TypeScript’.

Then we press ‘y’ to the question ‘Use class-style component syntax’.

If we want to be able to create class-style Vue.js components in an existing project, we can install the vue-class-component package by running:

npm install --save vue vue-class-component

Then we can create a class-style component by writing:

<template>
  <div>
    <button @click="decrement">-</button>
    {{ count }}
    <button @click="increment">+</button>
  </div>
</template>

<script>
import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class Counter extends Vue {
  count = 0

  increment() {
    this.count++
  }

  decrement() {
    this.count--
  }
}
</script>

We imported the Component decorator from vue-class-component package and used it to modified our class to turn it into a component.

Also, we created the Counter class that extends the Vue class.

Like with regular single-file components, we have to export the component code. In this case, we export a class instead of an object with the export keyword.

Then we can have members inside it, including the count state and the increment and decrement methods.

The template section is the same as regular single-file components.

We have the @click directive that calls methods, except the methods are in a class rather than an object.

The count is displayed in a template.

Class-style components is an alternative syntax for creating single-file components.

We can use the vue-class-component package to create class-style components.

The Component decorator and the Vue class lets us create the component class.

The members are accessible in templates as with regular single-file components.

Leave a Reply

Your email address will not be published. Required fields are marked *