Vue的TS风格书写

163 阅读1分钟
// TS使用Component等,需要在vue-property-decorator中引用
// vue-property-decoratorom是Components装饰器


import { Component, Vue, Prop, Watch} from "vue-property-decorator";
import Child from "/path";
//使用的组件放在@Component里面
@Component({
    components: {
        Child,
    },
})
//暴露Vue组件
export default class ComponentName extends Vue{
    /* props */
    @Prop({type: String,default:''}) private msg!:String;
    /* data */
    private count: number = 10;
    /* computed */
    private get money():number {
        return this.count;
    }
    /* watch */
    @Watch("count")
    private onCountChanged(newValue: number,oldValue: number):void{}
    /* methods */
    private handleCountChange(){}
    /* hooks */
    private created(){
    }
}
1.TS暴露组件需要定义一个类extends Vue,并从装饰器中引入Component
2.Prop传值要先从vue-property-decorator引入Prop
使用的时候需要@Prop后面跟TS的数据类型定义
3.JS中数据需要放在data中,TS风格直接用private 数据名: 数据类型 = ;
4.computed:private get money():{}
5.methods:private methodsname(){}
6.watch:@watch("count") private watchname(newValue: number,oldValue: number): void {}
7.生命周期函数:private 周期(){}

自己按照TS代码风格写的组件练习:

状态灯组件:
<template>
    <div class="alarm_notice">
        <span :class="statusClassName"></span>
    </div>
</template>

<script lang="ts">
import Vue from 'vue';//引用Vue
import { Component, Prop } from 'vue-property-decorator';//从装饰器import

interface OptionsItem {
    status: (number | string); 
    className: string;
}
export default class ComponentName extends Vue {

    @Prop({ type: [String, Number], default: '', })
    private readonly status!: number | string;

    @Prop({ type: Array, default: () => [{
        status: online,
        className: 'online',       
    }, {
        status: offline,
        className: 'offline',
    }, 
    ], })
    private readonly options!: OptionsItem[];

    get statusClassName(): string {
        const opt = this.options.find((v: OptionsItem) => v.status === this.status);
        return opt ? opt.className : '';
    }
}
</script>

<style lang="less" scoped>
.alarm_notice {  
    display: inline-block;
    .offline {
    }
    .online {