Get Started Writing Class-based Vue.js Apps in TypeScript
Vue.js 3.0 and TypeScript are a powerful alliance
Vue.js 3.0 will bring improved support to TypeScript users, including native support for class-based components and better type inference. But you can now start writing Vue applications using TypeScript using Vue CLI, the command line tool of Vue.
Advantages of Class-based Components and TypeScript
The class-based components in Vue.js can be written using the TypeScript class, which provides better type checking and maintainability. These classes can be declared using the vue-property-decorator
decorator in the @Component
package.
vue-property-decorator
package can further enhance class-based components. These include @Prop
for declaring props as class attributes, @Emit
for emitting events from class methods, and @Watch
for creating observers.
Advantages of TypeScript and Vue.js
TypeScript is used in conjunction with Vue.js with multiple advantages, including static type checking for early detection of errors, better autocomplete, navigation and refactoring services, and providing more structured and extensible code for complex applications library.
Last September, Evan You (the creator of Vue.js) announced plans for the next major version of the library. Vue 3.0 will bring an improved experience to TypeScript users, including native support for class-based components, and better support for type inference when writing code.
The good news is that you don't have to wait until the release of 3.0 (expected in Q3 2019) to start writing Vue apps using TypeScript. Vue's command line tool Vue CLI provides the option to start a project using the preconfigured TypeScript build tool and includes the officially supported vue-class-component
module that allows you to write Vue components as TypeScript classes.
This article assumes that you are familiar with the basics of Vue and TypeScript. Let's see how you start leveraging static typing and class-based components today.
Create Vue TypeScript Project
One of the obstacles to getting started with TypeScript may be configuring the necessary build tools. Thankfully, Vue CLI solved this problem for us. We can use it to create a project for us where the TypeScript compiler is set up and ready.
Let's briefly introduce the process of using TypeScript to support creating new Vue projects.
Run the following command from the terminal/command line (and assuming you have Node.js installed) to install Vue CLI globally:
npm install -g @vue/cli
Next, let's create a new project and specify the project name:
vue create vue-typescript-demo
This will also be the name of the subfolder for the installation project. After pressing
Select the manual option and you will see a further set of options. The necessary option is of course TypeScript, but you may also want to choose Vuex as we'll look at some Vuex-specific decorators later.
After selecting the project option, the next screen will ask you if you want to use class style component syntax. Say "yes" to this. You will then be asked if you want to "use Babel with TypeScript for polyfills for automatic detection". This is a good idea for projects that you will support older browsers. Answer the rest of the questions as needed and the installation process should begin.
Instructions on Editor/IDE Support
Many code editors and IDEs now support TypeScript. In paid solutions, JetBrains software (such as WebStorm, PhpStorm) has excellent support for both Vue and TypeScript. If you're looking for a free alternative, I recommend Microsoft's Visual Studio Code: In conjunction with the Vetur extension, it provides excellent autocomplete and type checking.
Class-based components
Let's first look at how to write Vue components using classes. While this feature is not limited to TypeScript, using class-based components helps TS to provide better type checking, and in my opinion, it makes the components simpler and easier to maintain.
Let's look at the syntax. If you followed the steps in the previous section and created a new project using the Vue CLI, go to the project directory, go to the src subfolder, and open App.vue. What we are interested here is the <script>
section because it is the only different part from the standard Vue Single File Component (SFC).
npm install -g @vue/cli
Note that the <script>
tag itself has the ts
attribute set to lang
. This is very important for the build tool and your editor to correctly interpret the code as TypeScript.
In order to declare a class-based component, you need to create a class that extends Vue (here it is imported directly from the vue-property-decorator
package instead of the vue
module).
Class declarations need to start with @Component
decorator:
vue create vue-typescript-demo
You may have noticed that in the code from the App.vue
component, the decorator can also accept an object that can be used to specify component, props, and filter options:
import { Component, Vue } from 'vue-property-decorator'; import HelloWorld from './components/HelloWorld.vue'; @Component({ components: { HelloWorld, }, }) export default class App extends Vue {}
Data attributes
When declaring an object-based component, you will be familiar with functions that must declare the component's data properties as returning a data object:
@Component class MyComponent extends Vue {}
…For class-based components, we can declare data attributes as normal class attributes:
@Component({ components: { MyChildComponent }, props: { id: { type: String, required: true } }, filters: { currencyFormatter } }) class MyComponent extends Vue {}
Computing properties
Another advantage of using classes as components is the cleaner syntax for declaring computed properties, using the getter method:
{ data: () => ({ todos: [], }) }
Similarly, you can create writable computed properties by using the setter method:
@Component class TodoList extends Vue { todos: []; }
Method
Component methods can be declared in a similarly concise way, as class methods:
npm install -g @vue/cli
In my opinion, the simple syntax for declaring methods, data attributes, and computed attributes makes writing and reading class-based components better than the original object-based components.
Decorators
We can go a step further and use the additional decorator provided by the vue-property-decorator
package. It provides six additional decorators for writing class-based components:
@Emit
@Inject
@Model
@Prop
@Provide
@Watch
Let's take a look at the three you might find the most useful.
@Prop
You can declare your props as a class property using the @Prop
decorator instead of passing the props configuration object to the @Component
decorator.
vue create vue-typescript-demo
Like other decorators, @Prop
can accept various parameters, including type, type array or option object:
import { Component, Vue } from 'vue-property-decorator'; import HelloWorld from './components/HelloWorld.vue'; @Component({ components: { HelloWorld, }, }) export default class App extends Vue {}
When used with TypeScript, you should add a non-empty operator (!) to your prop name to tell the compiler that the prop will have non-empty values (because TS does not know that these values will be passed to when initializing the component In the component):
@Component class MyComponent extends Vue {}
Note that as shown above, you can completely put the decorator and attribute declaration on one line if you prefer.
@Emit
Another convenient decorator is @Emit
, which allows you to issue events from any class method. The emitted event will use the method's name (the camelCase name will be converted to kebab-case), unless the alternative event name is passed to the decorator.
If the method returns a value, the value will be issued as the payload of the event, as well as any parameters passed to the method.
@Component({ components: { MyChildComponent }, props: { id: { type: String, required: true } }, filters: { currencyFormatter } }) class MyComponent extends Vue {}
The above code will emit a add-todo
event with the payload of the value of this.newTodo
.
@Watch
Creating an observer with this decorator is very simple. It accepts two parameters: the name of the observed property and an optional option object.
{ data: () => ({ todos: [], }) }
Summary
I hope this article shows you that it is not necessarily laborious to start writing Vue applications using TypeScript. By starting a new project using the CLI, you can quickly set up the necessary build tools. Including support for class-based components and additional decorators will enable you to write concise, idiomatic TypeScript right away!
Want to learn Vue.js from scratch? Use SitePoint Premium to get a complete collection of Vue books covering the basics, projects, tips and tools, and more. Join now for just $9 per month or try our 7-day free trial.
FAQs (FAQ) about class-based Vue.js using TypeScript
What are the benefits of using TypeScript and Vue.js?
TypeScript provides static typing, which can be a significant advantage when developing large applications. It helps catch errors early in the development process, making the code more robust and easier to maintain. TypeScript also provides better automatic completion, navigation and reconstruction services to make the development process more efficient. When used with Vue.js, TypeScript allows for a more structured and extensible code base, making it easier to manage and develop complex applications.
How to set up a Vue.js project using TypeScript?
Setting up a Vue.js project with TypeScript involves several steps. First, if you don't have Vue CLI installed, you need to install it. Then, use the Vue CLI to create a new project and select TypeScript as the feature during the creation process. The Vue CLI will set up the TypeScript configuration for you. You can then start writing Vue components using TypeScript.
What are the class-based components in Vue.js?
The class-based components in Vue.js is a way to define components using ES6 classes. This approach can make your components easier to read and understand, especially for developers from a background in object-oriented programming. Class-based components also work well with TypeScript, allowing you to take advantage of TypeScript's capabilities, such as static types and interfaces.
How to use TypeScript to define a class-based component in Vue.js?
To define class-based components using TypeScript in Vue.js, you need to use the vue-class-component
decorator. This decorator allows you to write components as ES6 classes. In a class, you can define data, methods, and lifecycle hooks as you would in a regular Vue component.
Can I use the Vue.js directive in a class-based component?
Yes, you can use the Vue.js directive in class-based components. The syntax is the same as in regular Vue components. You can use v-model
, v-if
, v-for
and other instructions in the template.
How to use props in class-based components?
In a class-based component, you can define props using the @Prop
decorator. This decorator allows you to specify the type of prop and whether it is required or has a default value.
How to use computed properties in a class-based component?
In a class-based component, you can define computed properties as a getter method in a class. The result of the getter method will be cached and recalculated only if its dependencies change.
How to use observers in class-based components?
In a class-based component, you can use the @Watch
decorator to define observers. This decorator allows you to specify the attributes to observe and the methods to be called when the attribute changes.
Can I use mixin in a class-based component?
Yes, you can use mixin in class-based components. You can define mixin as a class and include it in your component using the @Mixins
decorator.
How to use the Vue.js combination API with TypeScript?
Vue.js combination API works well with TypeScript. You can define your reactive data and functions within the setup
method and set the type for it using TypeScript. This allows you to take advantage of TypeScript's static typing and autocomplete capabilities to make your code more robust and easier to develop.
The above is the detailed content of Get Started Writing Class-based Vue.js Apps in TypeScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
