Vue學習(二十五)TS支援
阿新 • • 發佈:2021-10-11
如何在vue中使用TS
通過官網可以瞭解到,在vue中使用ts只需要使用npm安裝ts就好
在使用TS的vue中基礎語法
要讓 TypeScript 正確推斷 Vue 元件選項中的型別,您需要使用Vue.component
或Vue.extend
定義元件,或者宣告元件時你更喜歡基於類的 API,則可以使用官方維護的vue-class-component裝飾器
import Vue from 'vue'
import Component from 'vue-class-component'
// @Component 修飾符註明了此類為一個 Vue 元件
@Component({
// 所有的元件選項都可以放在這裡
template: '<button @click="onClick">Click!</button>'
})
export default class MyComponent extends Vue {
// 初始資料可以直接宣告為例項的 property
message: string = 'Hello!'
// 元件方法也可以直接宣告為例項的方法
onClick (): void {
window.alert(this.message)
}
}
實戰一:
<script lang="ts">
import {
Component,
Vue,
Watch,
} from 'vue-property-decorator';
import gamedownload from '@/common/components/download.vue';
@Component({
components: {
gamedownload,
},
})
export default class App extends Vue {
giftList: any = {};
unAcquireCount: number = 0;
showMask: Boolean = false;
cdkey: string = '' ;
gameName: String = '';
gameIcon: String = '';
// 複製
copy() {
const that = this;
};
// 初始化列表
async initList() {
const gameId = getUrlKey('gameId');
const response = await this.$requestApi.getGameGiftList(gameId);
if (response.result == 1) {
this.giftList = response.giftList;
this.unAcquireCount = response.unAcquireCount;
this.gameName = response.gameName.length > 6 ? response.gameName.substring(0, 6) + '..' : response.gameName;
this.gameIcon = response.gameIcon;
if (response.gameName) {
ksBridge.setPageTitle({
title: `${response.gameName}福利禮包`,
});
}
}
};
mounted() {
this.initList();
ksBridge.on({
type: 'native_foreground',
handler: this.initList,
});
ksBridge.on({
type: 'native_reentry',
handler: this.initList,
});
}
}
</script>
<style lang="less">
@import "./index.less";
</style>
實戰二:
<script lang="ts">
require('./index.less')
import { Component, Vue, Emit } from 'vue-property-decorator';
interface ruleItem{
title: string,
desc: Array<string>,
hasOpen?: boolean
}
@Component({})
export default class App extends Vue {
ruleList: Array<ruleItem> = [ ];
triggerDesc(idx:number){
this.ruleList[idx]['hasOpen'] = !this.ruleList[idx]['hasOpen'];
this.$forceUpdate();
}
}
</script>
注意:元件的屬性不必放在data中,方法不必放在methods中