虽然 vue2.x
对typescript的支持还不是非常完善,但是从今年即将到来的3.0版本在github上的仓库 看,为ts提供更好的官方支持应该也会是一个重要特性,那么,在迎接3.0之前,不妨先来看看目前版本二者的搭配食用方法吧~
创建项目
vue cli
应该是目前相对比较好的方式,在使用 vue create
创建新项目时,对 preset
选择 manually select features
选项,之后添加 typescript
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> <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>
interfaces
这样的文件夹,充分利用ts的接口和类来使项目有更好的组织结构,可读性和维护性。另一种选择
其实当然也可以不使用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内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!
如对本文有疑问, 点击进行留言回复!!
轻松解决 org.apache.taglibs.standard.tlv.JstlCoreTLV 困惑
vert实践五——Json?Protocol Buffer?FlatBuffers?
[基于tensorflow的人脸检测] 基于神经网络的人脸检测8——验证训练好的神经网络
selenium + ajax抓取英雄联盟全部英雄的详细信息及多线程保存全部皮肤图片到本地
网友评论