关于vue.js:在vue项目中写Typescript

8次阅读

共计 1218 个字符,预计需要花费 4 分钟才能阅读完成。

两种形式:

  • extends 写法 (不应用装璜器) —- 更贴近于 vue 语法
import Vue from 'vue'
import MainHeader from './header.vue'
import MainContent from './content.vue'

interface User {
  name: string,
  age: number
}

export default Vue.extend({
  components: {
    MainHeader,
    MainContent
  },
  props: {
    testProps: {type: Object as () => User
    }
  },
  data () {
    return {show: false}
  },
  methods: {setShow (state: boolean): void {this.show = state}
  },
  computed: {num(): number {return this.count},
    name: {
      // 须要标注有 `this` 参加运算的返回值类型
      get(): string {return this.item.n},
      set(val: string) {this.item.n = val}
    }
  }
})
  • vue-property-decorator(装璜器语法) —- 贴近类的写法
import {Vue, Component, Watch} from 'vue-property-decorator'
interface KeyValue {
  c: string
  n: string
}

@Component({
  components: {
    MainHeader,
    MainContent
  }
})
export default class Test extends Vue {
  // data
  count: number = 1
  item: KeyValue = {
    c: '',
    n: ''
  }

  // computed
  get num(): number {return this.count}
  get name(): string {return this.item.n}
  // 留神,这里不能标返回值类型,就算写 void 也不行
  set name(val: string) {this.item.n = val}

  // watch
  @Watch('count')
  watchCount(newVal: number, oldVal: number): void {console.log(newVal)
  }
  @Watch('item.n')
  watchName(newVal: string, oldVal: string): void {console.log(newVal)
  }
  @Watch('item', { deep: true})
  watchItem(newVal: KeyValue, oldVal: KeyValue): void {console.log(newVal)
  }
  // methods
  reset(): void {this.$emit('reset')
  },
  getKey(): string {return this.item.c}
}
正文完
 0