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

Tutorial on Installing Nginx-RTMP Streaming Server on Ubuntu 14

1. RTMP RTMP streaming protocol is a real-time au...

Vue v-model related knowledge summary

​v-model is a Vue directive that provides two-way...

Turn off the AutoComplete function in the input box

Now we can use an attribute of input called autoco...

Native js to achieve star twinkling effect

This article example shares the specific code of ...

Convert XHTML CSS pages to printer pages

In the past, creating a printer-friendly version ...

CSS3 achieves cool 3D rotation perspective effect

CSS3 achieves cool 3D rotation perspective 3D ani...

A solution to a bug in IE6 with jquery-multiselect

When using jquery-multiselect (a control that tra...

Detailed explanation of various HTTP return status codes

When a request is sent to your server to display ...

Example of using the href attribute and onclick event of a tag

The a tag is mainly used to implement page jump, ...

Vue-cli framework implements timer application

Technical Background This application uses the vu...

js to realize the rotation of web page pictures

This article shares the specific code of js to re...

Solution to mysql login warning problem

1. Introduction When we log in to MySQL, we often...

How to implement digital paging effect code and steps in CSS

A considerable number of websites use digital pagi...

Introducing icons by implementing custom components based on Vue

Preface In project development, there are many wa...

How to add ansible service in alpine image

Use apk add ansible to add the ansible service to...