这篇文章主要为大家展示了在Vue.js中如何使用TypeScript,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带大家一起来研究并学习一下“在Vue.js中如何使用TypeScript”这篇文章吧。
vue是什么软件
Vue是一套用于构建用户界面的渐进式JavaScript框架,Vue与其它大型框架的区别是,使用Vue可以自底向上逐层应用,其核心库只关注视图层,方便与第三方库和项目整合,且使用Vue可以采用单文件组件和Vue生态系统支持的库开发复杂的单页应用。
虽然 vue2.x
对TypeScript的支持还不是非常完善,但是从今年即将到来的3.0版本在GitHub上的仓库vue-next 看,为TS提供更好的官方支持应该也会是一个重要特性,那么,在迎接3.0之前,不妨先来看看目前版本二者的搭配食用方法吧~
创建项目
虽然GitHub上有各种各样相关的Starter,但是使用
Vue CLI
应该是目前相对比较好的方式,在使用vue create
创建新项目时,对preset
选择Manually select features
选项,之后添加TypeScript
如果想在vue应用中完整使用ES6中提供的类特性,那么在
class-style component syntax
处选择Y(本文主要介绍选择Y的情况)对于
Babel
来说,一般情况选择使用,而linter / formatter
的具体选择可根据项目需求,此处不多说明
进入项目
创建完成后,看一看 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> <scriptlang="ts"> importVuefrom'vue' importComponentfrom'vue-class-component' //Definethecomponentinclass-style @Component exportdefaultclassCounterextendsVue{ //Classpropertieswillbecomponentdata count=0 //Methodswillbecomponentmethods increment(){ this.count++ } decrement(){ this.count-- } } </script>
而 vue-property-component
则完全依赖于前者,提供了除 @Component
外的其他几种装饰器,比如 @Prop
import{Vue,Component,Prop}from'vue-property-decorator' @Component exportdefaultclassYourComponentextendsVue{ @Prop(Number)readonlypropA:number|undefined @Prop({default:'defaultvalue'})readonlypropB!:string @Prop([String,Boolean])readonlypropC:string|boolean|undefined }
再来一个二者结合的简单例子吧:
<template> <divclass="hello"> <h2>{{msg}}</h2> <h2>{{fullName}}</h2> <button@click="reverseStr()">Reverse</button> </div> </template> <scriptlang="ts"> import{Component,Prop,Vue,Watch}from'vue-property-decorator'; @Component exportdefaultclassHelloWorldextendsVue{ @Prop()privatemsg!:string; firstName="rapt"; lastName="azure"; mounted(){ console.log('mounted'); } //Computedproperty getfullName():string{ returnthis.firstName+this.lastName; } //Method reverseStr(){ this.firstName=this.firstName.split('').reverse().join(''); this.lastName=this.lastName.split('').reverse().join(''); } } </script>
此时,你的vue项目已经有fully-typed的可能了,当然也会有更好的自动补全以及错误提示。
为了更好的确定类型,可以创建例如
interfaces
这样的文件夹,充分利用ts的接口和类来使项目有更好的组织结构,可读性和维护性。
另一种选择
其实当然也可以不使用class风格啦,这样的话,就和平时熟悉的vue更为相似了,而对类型当然也是完全支持的。这里也提供一个简单的例子吧~<template>
<divclass="hello"> <h2>{{msg}}</h2> <h2>{{test}}</h2> </div> </template> <scriptlang="ts"> importVuefrom'vue'; exportdefaultVue.extend({ name:'HelloWorld', props:{ msg:String, }, data(){ return{ test:"HellofromTS"asstring } }, methods:{ pressMe():string{ returnthis.test+'br' } } }); </script>
其他的话
本文只是简要探讨了在Vue.js中使用TypeScript的可能性,更多的相关内容在官方文档里可以找到哦,或者也可以多去Github的Vue区,TS区逛逛呢~
TypeScript的出现为JavaScript的生态带来了新活力,不管是前端三大框架Vue,React,Angular,还是Node系的后端框架比如Nest和Express,都在积极拥抱TS,希望以后整个生态会发展得越来越好吧~
以上就是关于“在Vue.js中如何使用TypeScript”的内容,如果改文章对你有所帮助并觉得写得不错,劳请分享给你的好友一起学习新知识,若想了解更多相关知识内容,请多多关注恰卡编程网行业资讯频道。