使用TypeScript開發Uni-App項目
- 使用TypeScript開發Uni-App項目
-
- 通過HbuiderX建立uni-app項目
- 常見裝飾器的使用
- 簡單的Demo頁面
- 幾個注意問題
使用TypeScript開發Uni-App項目
通過HbuiderX建立uni-app項目
在新項目的vue檔案中使用内聯ts
按需引入vue裝飾器
不管幹啥先把下面這句話加上。
常見裝飾器的使用
export default class Idnex extends Vue{
private title:String = 'myTitle'; //響應式屬性
private num:Number = 123; //對标之前的data函數傳回的對象
get age():Number{ //計算屬性
return this.num;
}
onLoad(){
this.printTitle();
let a:string = '123';
}
@Watch('title') //watch,此處是監聽title的變化
titleChange(newVal:Number,oldVal:Number){
console.log(newVal,oldVal);
}
printTitle():void{ //methods
console.log('hahahhhaha')
}
}
簡單的Demo頁面
<template>
<view class="content" @click.self="printTitle">
<image class="logo" src="/static/logo.png" @click.stop="title = 'ggg'"></image>
<view class="text-area">
<text class="title">{{title}}</text>
<view>{{age}}</view>
</view>
</view>
</template>
<script lang="ts">
import { Component,Vue ,Watch} from "vue-property-decorator";
@Component({})
export default class Idnex extends Vue{
private title:String = 'myTitle'; //響應式屬性
private num:Number = 123; //對标之前的data函數傳回的對象
get age():Number{ //計算屬性
return this.num;
}
onLoad(){
this.printTitle();
let a:string = '123';
}
@Watch('title') //watch,此處是監聽title的變化
titleChange(newVal:Number,oldVal:Number){
console.log(newVal,oldVal);
}
printTitle():void{ //methods
console.log('hahahhhaha')
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
幾個注意問題
- 首先要在Hbuiderx裡安裝有關typeScript的幾個插件,具體就兩個一次性都裝上。
- 如果是直接在HbuiderX裡面開發編輯無需再額外安裝Vue,vue-property-decorator等
- 如果是通過VSCode等編輯器則需要額外安裝vue-property-decorator和vue-class-decorator
- @Component({})是必須要的,如果缺失在H5 端不會産生什麼問題但是如果編譯為微信小程式則會報錯’mp-weixin’未定義,其它端未做驗證。
- 看了一些介紹和Demo也可以通過vue-cli和uni-app結合的方式使用ts開發uni-app項目。有興趣的可以去搗鼓搗鼓。