If we prefer to use classes, we can use the class-based components API that comes with Vue.
In this article, we’ll look at how to developing Vue apps with class-based components.
Getting Started
We can create our Vue project as usual with the Vue CLI’s vue create
command.
Then we install the vue-class-component
library by running:
npm install --save vue vue-class-component
with NPM or:
yarn add --save vue vue-class-component
with Yarn.
If we’re using TypeScript, we also have to add the experimentDecorators
option to tsconfig.json
so we can use decorators.
We should put the following into the compilerOptions
property of it:
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"strict": true,
"experimentalDecorators": true
}
}
And if we’re using Babel, we’ve to install the @babel/plugin-proposal-decorators
and @babel/plugin-proposal-class-properties
packages by running:
npm install --save-dev @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties
In .babelrc
, we add:
{
"plugins": [
["@babel/proposal-decorators", { "legacy": true }],
["@babel/proposal-class-properties", { "loose": true }]
]
}
to let us add decorators and class properties that aren’t bound to the class.
Create Our First Component
Now we can use the vue-class-component
modile to create our first class-based component.
For instance, we can write:
components/HelloWorld.vue
<template>
<div>{{ message }}</div>
</template>
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class HelloWorld extends Vue {
message = 'Hello World'
}
</script>
App.vue
<template>
<div id="app">
<HelloWorld />
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld,
},
};
</script>
In HelloWorld.vue
, we have the HelloWorld
class has the message
property that isn’t bound to the HelloWorld
instance.
We can use that in the template.
Also, we can add the data
method and return an object with the reactive properties:
<template>
<div>{{ message }}</div>
</template>
<script>
import Vue from "vue";
import Component from "vue-class-component";
@Component
export default class HelloWorld extends Vue {
data() {
return {
message: "Hello World",
};
}
}
</script>
The message
property returned with data
is reactive, so we can use it in the template.
To add methods, we add them as class methods:
<template>
<div>
<button @click="increment">increment</button>
{{ count }}
</div>
</template>
<script>
import Vue from "vue";
import Component from "vue-class-component";
@Component
export default class HelloWorld extends Vue {
count = 0;
increment() {
this.count++;
}
}
</script>
We add the increment
method to increase the count
reactive property by 1.
And we pass that into the @click
directive as its value.
Conclusion
We can add class-based components in our Vue app with the vue-class-component
library.