Typescript is static typing. Once a type is defined, it cannot be changed.

Using it in VUE will help us find errors faster, and it will be a little headache in initial learning, but it will improve code quality and work efficiency after getting familiar with it.

The installation

Vue CLI 3 can generate new projects using TypeScript. Creation method:

  // 1. If the Vue CLI is not installed, install it first
  npm install --global @vue/cli

  // Create a new project and select the "Manually select features "option
  vue create my-project-name
Copy the code
  • Choose the manual

  • Select typescript(press spacebar to select it)

And just keep going…

Based on using

Component options


<script lang="ts">

import Vue from 'vue'

export default Vue.extend({
	// Type inference is enabled. })export default {
	// There will be no type inference because the options for the VUE component are uncertain. } </script>Copy the code

Kind of the way

  • Component use
import Vue from 'vue'
import Component from 'vue-class-component' // If not, you need to download it yourself

The @component modifier indicates that this class is a Vue Component
@Component({
	navBar,siderBar,...
})

export default class MyComponent extends Vue {}Copy the code
  • Define variables
export default class MyComponent extends Vue {
	// The initial data can be declared directly as the instance's property
	message: string = 'Hello World! '
   	title: string = 'Vue'
}
Copy the code
  • Calculate attribute
export default class MyComponent extends Vue {
  get count: number () {
    return this.num * 2}}Copy the code
  • Methods using
export default class MyComponent extends Vue {
   Component methods can also be declared directly as instance methods
   onClick (): void { // void indicates that the function returns no value
      window.alert(this.message)
   }
}
Copy the code
  • Mark Prop
import Vue, { PropType } from 'vue'
interface IUserInfoProp { 
  title: string,
  okMessage: string,
  cancelMessage: string
}
const Component = Vue.extend({
  props: {
    userInfo: {
      type: Object as PropType<IUserInfoProp>, / / oh
      require: true}}})Copy the code