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></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></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!

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.


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

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
