Getting Started Tutorial on Using TS (TypeScript) in Vue Project

Getting Started Tutorial on Using TS (TypeScript) in Vue Project

Recently, the project needs to transform the original vue project with the use of ts. This should be the development trend of medium and large projects. I saw a good introductory tutorial, combined it with some expansion records. This article explains from installation to Vue component writing, which is suitable for getting started.

1. Introducing Typescript

npm install vue-class-component vue-property-decorator --save
npm install ts-loader typescript tslint tslint-loader tslint-config-standard --save-dev

vue-class-component : extends vue to support typescript, and supports ts in a declarative way

vue-property-decorator : Extend more decorators based on vue-class-component

ts-loader : enables webpack to recognize ts files

tslint-loader : tslint is used to constrain file encoding

tslint-config-standard : tslint configures standard style constraints

2. Configuration file webpack configuration

The configuration location varies depending on the project. If the project is created by vue cli 3.0, it needs to be configured in vue.config.js. If it is a version below 3.0, it needs to be configured in webpack.base.conf. (The following instructions are to change in the webpack.base.conf file)

Add .ts to resolve.extensions to introduce ts files into the code without writing the .ts suffix

  resolve: {
    extensions: ['.js', '.vue', '.json', '.ts'],
    alias: {}
  }

Add ts rules in module.rules

module: {
    rules:
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        enforce: 'pre',
        loader: 'tslint-loader'
      },
      {
        test: /\.tsx?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
        options:
          appendTsSuffixTo: [/\.vue$/]
        }
      }
    ]
  }

tsconfig.json configuration
ts-loader will retrieve the tsconfig.json file and parse the ts file according to the rules in it. For detailed configuration, please refer to https://www.tslang.cn/docs/handbook/tsconfig-json.html
Paste the test project tsconfig.json file

{
  // Compiler options "compilerOptions": {
    // Output directory "outDir": "./output",
    // Whether to include sourceMap that can be used for debugging
    "sourceMap": true,
    // Parse in strict mode "strict": false,
    // Module system used "module": "esnext",
    // How to handle modules "moduleResolution": "node",
    // Compile and output target ES version "target": "es5",
    // Allow default imports from modules that do not set a default export "allowSyntheticDefaultImports": true,
    // Treat each file as a separate module "isolatedModules": false,
    // Enable decorators "experimentalDecorators": true,
    // Enable design type metadata (for reflection)
    "emitDecoratorMetadata": true,
    // Error "noImplicitAny": false, if there is an implicit any type in expressions and declarations
    // Not all return paths of a function return a value and an error is reported.
    "noImplicitReturns": true,
    // Import external helper libraries from tslib: such as __extends, __rest, etc. "importHelpers": true,
    // Print file names during compilation "listFiles": true,
    // Remove comments "removeComments": true,
    "suppressImplicitAnyIndexErrors": true,
    // Allow compilation of javascript files "allowJs": true,
    // Base directory for parsing non-relative module names "baseUrl": "./",
    //Specify the path of special modules "paths": {
      "jquery": [
        "node_modules/jquery/dist/jquery"
      ]
    },
    // List of library files that need to be introduced during compilation "lib": [
      "dom",
      "es2015",
      "es2015.promise"
    ]
  }
}

tslint.json configuration adds a new tslint.json file in the directory. Since we have installed tslint-config-standard before, we can directly use the rules in tslint-config-standard. The file is as follows:

  {
    "extends": "tslint-config-standard",
    "globals": {
      "require": true
    }
  }

3. Let the project recognize .ts

Since TypeScript does not support files with the *.vue suffix by default, you need to create a vue-shim.d.ts file when introducing it in a vue project and put it in the root directory

declare module '*.vue' {
  import Vue from 'vue';
  export default Vue;
}

4. Writing vue components

Most methods in vue components are changed to use @xxx (decorator) to indicate what data is currently defined, similar to injection in ng. The business logic js part can be directly written in ts.

Basic writing

The writing of template and style remains unchanged, but the script module has been changed. The basic writing is as follows:

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
@Component
export default class Test extends Vue {
  
};
</script>
  • lang="ts" : The current language under script statement is ts
  • @Component : Indicates that this class is a vue component
  • export default class Test extends Vue : export the current component class that inherits vue

Define data in data()

The data in data is changed from the original data() method to be defined directly in the object

export default class Test extends Vue {
 public message1: string = "heimayu";
 public message2: string = "It's really beautiful";
}

Props

Props is not as comfortable as data, because it needs to use decorators, which can be written as follows

@Prop()
propA:string

@Prop()
propB:number

$emit value

Without parameters

 // Original writing: this.$emit('bindSend')
  // Now just write this.bindSend()
  // Multiple definitions @Emit()
  bindSend():string{
      return this.message
  }

Methods with parameters

  // Original writing: this.$emit('bindSend', msg)
  // Now write directly: this.bindSend(msg)
  // Multiple definitions below @Emit()
  bindSend(msg:string){
      // to do something
  }

emit with parameters

  // Here, test is the @ event name that changes the component reference. In this case, you should write @test instead of @bindSend2
  @Emit('test)
  private bindSend2(){
      
  }

watch observation data

  //Original writing watch:{}

  @Watch('propA',{
      deep:true
  })
  test(newValue:string,oldValue:string){
      console.log('propA value changed' + newValue);
  }

computed properties

public get computedMsg(){
      return 'Here is the calculated property' + this.message;
 }
public set computedMsg(message: string) {
 }

Complete code example

<template>
  <div class="test-container">
    {{message}}
    <input type="button" value="Click to trigger parent method" @click="bindSend"/>
    <input type="button" value="Click to trigger parent method" @click="handleSend"/>
    <input type="button" value="Click to trigger parent method" @click="bindSend2"/>
    <!-- <Hello></Hello> -->
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch, Emit } from "vue-property-decorator";
import Hello from "./HelloWorld.vue";
// Indicate that this class is a vue component @Component({
  components:
    Hello
  }
})
export default class Test extends Vue {
  // The data in the original data is expanded and written here public message: string = "asd";
  //Expand the data in the original props to write @Prop({
    type: Number,
    default: 1,
    required: false
  })
  propA?: number
  @Prop()
  propB:string
  //Original computed
  public get computedMsg(){
      return 'Here is the calculated property' + this.message;
  }
  public set computedMsg(message: string) {
  }
  //Original watch attribute @Watch('propA',{
      deep:true
  })
  public test(newValue:string,oldValue:string){
      console.log('propA value changed' + newValue);
  }
  // In the past, when you needed to pass a value to the parent, you could just use emit in the method. Now you need to use emit to handle @Emit()
  private bindSend():string{
      return this.message
  }
  @Emit()
  private bindSend1(msg:string,love:string){
      // If you don't want to process, you don't need to write the following, the parameters will be automatically returned // msg += 'love';
    // return msg;
  }
  //The original method in methods is laid out public handleSend():void {
      this.bindSend1(this.message,'love');
  }
  // The parameters in emit here indicate what the parent accepts, similar to the previous $emit('parent defined method')
  @Emit('test')
  private bindSend2(){
      return 'This can be accepted by test';
  }
}
</script>

This concludes this article about the introductory tutorial on using ts (typescript) in vue projects. For more relevant vue typescript introductory content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • TypeScript Basics Tutorial: Triple Slash Instructions
  • Vue's new partner TypeScript quick start practice record
  • Detailed explanation of TypeScript best practices before Vue 3.0
  • TypeScript Introduction - Interface
  • TypeScript Basic Data Types
  • Introduction to TypeScript

<<:  MySQL foreign key (FOREIGN KEY) usage case detailed explanation

>>:  How to make a tar file of wsl through Docker

Recommend

Detailed explanation of how to exit Docker container without closing it

After entering the Docker container, if you exit ...

Nginx configuration based on multiple domain names, ports, IP virtual hosts

1. Type introduction 1.1 Domain-based virtual hos...

Nginx configuration PC site mobile site separation to achieve redirection

Use nginx to configure the separation of PC site ...

Detailed explanation of the cache implementation principle of Vue computed

Table of contents Initialize computed Dependency ...

Detailed explanation of the difference between uniapp and vue

Table of contents 1. Simple page example 2.uni-ap...

How to quickly deploy Gitlab using Docker

1. Download the gitlab image docker pull gitlab/g...

Introduction to setting up Tomcat to start automatically on Linux system

1. Enter the /etc/init.d directory: cd /etc/init....

SELinux Getting Started

Back in the Kernel 2.6 era, a new security system...

Vue resets data to its initial state

In some cases, the data in data needs to be reuse...

Docker container data volume named mount and anonymous mount issues

Table of contents What is a container data volume...

Detailed explanation of nginx reverse proxy webSocket configuration

Recently, I used the webSocket protocol when work...

How to install mysql5.7.24 binary version on Centos 7 and how to solve it

MySQL binary installation method Download mysql h...