虽然 vue2.x 对TypeScript的支持还不是非常完善,但是从今年即将到来的3.0版本在GitHub上的仓库 vue-next 看,为TS提供更好的官方支持应该也会是一个重要特性,那么,在迎接3.0之前,不妨先来看看目前版本二者的搭配食用方法吧~
创建项目
进入项目
创建完成后,看一看 package.json ,可以发现 vue-class-component 和 vue-property-decorator 以及其他ts相关的modules都已被添加,其中: vue-class-component 可以让你使用class-style语法创建组件,比如以下代码:
<template> <div> <button @click="decrement">-</button> {{ count }} <button @click="increment">+</button> </div> </template> <script lang="ts"> import Vue from 'vue' import Component from 'vue-class-component' // Define the component in class-style @Component export default class Counter extends Vue { // Class properties will be component data count = 0 // Methods will be component methods increment() { this.count++ } decrement() { this.count-- } } </script>
而 vue-property-component 则完全依赖于前者,提供了除 @Component 外的其他几种装饰器,比如 @Prop
import { Vue, Component, Prop } from 'vue-property-decorator' @Component export default class YourComponent extends Vue { @Prop(Number) readonly propA: number | undefined @Prop({ default: 'default value' }) readonly propB!: string @Prop([String, Boolean]) readonly propC: string | boolean | undefined }
再来一个二者结合的简单例子吧:
<template> <div class="hello"> <h1>{{ msg }}</h1> <h1>{{ fullName }}</h1> <button @click="reverseStr()">Reverse</button> </div> </template> <script lang="ts"> import { Component, Prop, Vue, Watch } from 'vue-property-decorator'; @Component export default class HelloWorld extends Vue { @Prop() private msg!: string; firstName = "rapt"; lastName = "azure"; mounted() { console.log('mounted'); } // Computed property get fullName(): string { return this.firstName + this.lastName; } // Method reverseStr() { this.firstName = this.firstName.split('').reverse().join(''); this.lastName = this.lastName.split('').reverse().join(''); } } </script>
另一种选择
其实当然也可以不使用class风格啦,这样的话,就和平时熟悉的vue更为相似了,而对类型当然也是完全支持的。
这里也提供一个简单的例子吧~<template>
<div class="hello"> <h1>{{ msg }}</h1> <h1>{{ test }}</h1> </div> </template> <script lang="ts"> import Vue from 'vue'; export default Vue.extend({ name: 'HelloWorld', props: { msg: String, }, data() { return { test: "Hello from TS" as string } }, methods: { pressMe(): string { return this.test + 'br' } } }); </script>
其他的话
总结
到此这篇关于在Vue.js中使用TypeScript的文章就介绍到这了,更多相关Vue.js使用TypeScript内容请搜索呐喊教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持呐喊教程!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。