ts在vue2.x和vue3.0的使用

969 阅读1分钟

vue2.x中使用

Vue@2.x 要用上 ts 通常需要借助于 vue-property-decorator 这个库。

使用方式:

import Vue from 'vue'
import { Component, Prop } from 'vue-property-decorator';

@Component({
  template: '<button @click="onClick">Click!</button>'
})
export default class Test extends Vue {
  preStr: string = 'Hello!'

  @Prop({ type: String, default: 'world' })
  message: string

  onClick (): void {
    window.alert(this.preStr + this.message)
  }
}

Vue@3.x 中使用 ts

Vue@3.x + ts 的项目,只需通过 defineComponent 定义组件即可完美推断出 component options 中的类型:

import { defineComponent } from 'vue'

const Component = defineComponent({
  data() {
    return {
      preStr: 'hello!'
    }
  },
  props: {
    message: {
      type: String,
      required: true
    }
  },
  methods: {
    onClick() {
      this.preStr = 'hi!' // ok    preStr被推断成 string
      this.preStr = 123   // error number类型不能分配给string类型
      this.message = 'zz' // error message是read-only属性
    }
  }
})

对于 Composition Api 的支持度也很高:

import { defineComponent, ref, PropType } from 'vue';

export default defineComponent({
  props: {
    callback: {
      required: true,
      type: Function as PropType<(nums: number) => void>
    },
    message: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const nums = ref(0)

    props.callback(props.message)  // error callback的参数应该是number类型

    props.callback(nums.value)     // ok
  }
})