How to apply TypeScript classes in Vue projects

How to apply TypeScript classes in Vue projects

1. Introduction

TypeScript is based on the vue-class-component library, which is an official library launched by vue that supports the use of class to develop vue single-file components.

The main functions are as follows:

  • methods can be directly declared as member methods of a class
  • Computed properties can be declared as property accessors of a class
  • Initialized data can be declared as class attributes
  • data , render , and all Vue lifecycle hooks can be used directly as class member methods
  • All other properties need to be placed in the decorator

2. Use

vue-property-decorator mainly provides the following decorators

  • @Prop
  • @PropSync
  • @Model
  • @Watch
  • @Provide
  • @Inject
  • @ProvideReactive
  • @InjectReactive
  • @Emit
  • @Ref
  • @Component (provided by vue-class-component)
  • Mixins (provided by vue-class-component)

1. @Component

Component decorator It marks this class as a Vue component, so it cannot be omitted even if no options are set

If you need to define name , components , filters , directives , and custom properties, you can define them in Component decorator as follows:

import {Component,Vue} from 'vue-property-decorator'; 
import {componentA,componentB} from '@/components'; 
 
 @Component({ 
    components:{ 
        componentA, 
        componentB, 
    }, 
    directives: { 
        focus: 
            // Definition of instruction inserted: function (el) { 
                el.focus() 
            } 
        } 
    } 
}) 
export default class YourCompoent extends Vue{ 
    
} 


2. Computed, data, methods

data and methods attributes of the component are cancelled here. In the past, the attributes in the data return object and the methods in methods need to be defined directly in the Class as the attributes and methods of the class.

@Component 
export default class HelloDecorator extends Vue { 
    count: number = 123 // The class attribute is equivalent to the previous data 
 
    add(): number { // The class method is the same as the previous method this.count + 1 
    } 
 
    // Get the calculated attribute get total(): number { 
      return this.count + 1 
    } 
 
    // Set the calculated properties set total(param:number): void { 
      this.count = param 
    } 
} 

3. @props

The component receives the decorator of the attribute, which is used as follows:

import {Component,Vue,Prop} from vue-property-decorator; 
 
@Component 
export default class YourComponent extends Vue { 
    @Prop(String) 
    propA: string; 
     
    @Prop([String,Number]) 
    propB:string|number; 
     
    @Prop({ 
     type: String, // type: [String , Number] 
     default: 'default value', // usually a String or Number 
      //If it is an object or array. Default value is returned from a factory function // default: () => { 
      // return ['a','b'] 
      // } 
     required: true, 
     validator: (value) => { 
        return [ 
          'InProcess', 
          'Settled' 
        ].indexOf(value) !== -1 
     } 
    }) 
    propC: string; 
} 


4. @watch

It is actually the listener in Vue, as follows:

import { Vue, Component, Watch } from 'vue-property-decorator' 
 
@Component 
export default class YourComponent extends Vue { 
  @Watch('child') 
  onChildChanged(val: string, oldVal: string) {} 
 
  @Watch('person', { immediate: true, deep: true }) 
  onPersonChanged1(val: Person, oldVal: Person) {} 
 
  @Watch('person') 
  onPersonChanged2(val: Person, oldVal: Person) {} 
} 


5. @emit

The @Emit decorator provided by vue-property-decorator replaces $emit trigger of events in Vue, as follows:

import {Vue, Component, Emit} from 'vue-property-decorator'; 
    @Component({}) 
    export default class Some extends Vue{ 
        mounted(){ 
            this.$on('emit-todo', function(n) { 
                console.log(n) 
            }) 
            this.emitTodo('world'); 
        } 
        @Emit() 
        emitTodo(n: string){ 
            console.log('hello'); 
        } 
    } 

Conclusion

You can see that the syntax of the above typescript version of vue class is quite different from that of the usual javascript version. Class and decorators are used in many places, but in fact, the essence is the same. Only by constantly writing can you become proficient in it.

This is the end of this article on how to apply TypeScript in Vue projects. For more information on applying TypeScript in Vue projects, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • TypeScript Enumeration Type
  • Introduction to TypeScript basic types
  • Explain TypeScript enumeration types in detail
  • Detailed explanation of type protection in TypeScript
  • A brief discussion on TypeScript's type protection mechanism
  • Classes in TypeScript

<<:  Use of Linux passwd command

>>:  Detailed analysis of MySQL master-slave replication

Recommend

MySql Group By implements grouping of multiple fields

In daily development tasks, we often use MYSQL...

WeChat applet + ECharts to achieve dynamic refresh process record

Preface Recently I encountered a requirement, whi...

Detailed tutorial on deploying apollo with docker

1. Introduction I won’t go into details about apo...

How to use DQL commands to query data in MySQL

In this article, the blogger will take you to lea...

Analysis of HTTP interface testing process based on postman

I accidentally discovered a great artificial inte...

How to use webSocket to update real-time weather in Vue

Table of contents Preface About webSocket operati...

JS implements simple addition and subtraction of shopping cart effects

This article example shares the specific code of ...

The final solution to Chrome's minimum font size limit of 12px

I believe that many users who make websites will ...

MySQL 8.0.22 winx64 installation and configuration graphic tutorial

mysql 8.0.22 winx64 installation and configuratio...

Solution for Docker container not recognizing fonts such as Songti

Problem background: When using docker to deploy t...

Solution to the conflict between two tabs navigation in HTML

Let's start with a description of the problem...

Complete steps to set up automatic updates in CentOS 8

The best thing you can do for your data and compu...

CSS to achieve the small sharp corner effect of bubbles

Effect picture (the border color is too light, pu...