Vue学习(二十五)TS支持

如何在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中

参考

vue官网教程:TypeScript支持

Typescript中如何使用一些Vue的属性

 

vue+ts项目vue-property-decorator(装饰器)用法

 

原文地址:https://www.cnblogs.com/kunmomo/p/15393891.html