前言
在小程序上应用uniapp 然后引入ts ,你说香不香,哈哈哈
好了 先来一发教程:
官网下载 软件 https://uniapp.dcloud.io/
我创建的TS项目是,用cli 命令行创建的
全局安装vue-cli
npm install -g @vue/cli
创建uni-app
使用正式版(对应HBuilderX最新正式版)
vue create -p dcloudio/uni-preset-vue my-ts
选中 默认模板 (typeScript ) 然后 回车等待
然后在用编辑器打开
你会发现 目录是这样的:
小程序 page 里面就可以页面啦
在新项目的vue文件中使用内联ts
<script lang="ts">
按需引入vue装饰器
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')
}
}
简单的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>
其实我的index 页面是这样 的
<template>
<view class="content">
<image class="logo" :src="'../../static/logo.png'"></image>
<view>
<view v-for="(title, key) in titles" :key="key" class="title">{{title}}</view>
</view>
</view>
</template>
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
@Component
export default class Home extends Vue {
titles: string[] = ['title1', 'title2'];
onLoad() {
console.log(this.titles)
}
}
</script>
<style>
.content {
text-align: center;
height: 400upx;
}
.logo{
height: 200upx;
width: 200upx;
margin-top: 200upx;
}
.title {
font-size: 36upx;
color: #8f8f94;
}
</style>