vue2.x中使用typescript

2022-07-07 09:36:22
2024-04-18 01:58:31

vue-property-decorator的常用示例

在vue-property-decorator中有以下几个修饰符组成:

  • @Component
  • @Prop
  • @Model
  • @Emit
  • @Inject
  • @Provide

下面以JS写法和TS写法作为对比供大家参考

@Component

js写法

import { compA, compB } from '@/components';
export default {
    components: {
        compA,
        compB
    }
}

ts写法

import {Component,Vue} from 'vue-property-decorator';
import {compA,comptB} from '@/components';
@Component({
    components: {
        compA,
        compB
    }
})

export default class XXX extends Vue {
...
}

Prop

js写法

export default {
   props: (
       propA: String,
       propB: [Number, String],
       propC: {
           default: 'default value'
       }
   )
}

ts写法

import {Component, Vue, Prop} from 'vue-property-decorator';

@Component
export default class MyComponent extends Vue {
    @Prop(String) readonly propA: String | undefined
    @Prop([String, Number]) readonly propB: number | string | undefined
    @Prop({default: 'default value'}) readonly propC!: string   // 注意  这里的!标识这个prop一定是非空的
}

@Model
js写法

<my-comp v-model="checked" />  // 父组件引用

// 子组件

<input type="checkbox" @change="$emit('eventName', $event.target.checked)" :checked="checked">
export default {
    props: {
        checked: {
            type: Boolean
        }
    },
    model: {
        prop: 'checked',
        event: 'eventName'
    }
}

ts写法

import {Vue, Component, Model} from 'vue-property-decorator';
@Component
export default class Myconponent extends Vue {
    @Model('eventName', {type: Boolean}) readonly checked!: boolean
}

@Watch

js写法

export default {
    watch: {
        val1: [{
            handler: 'onValue1Change',
            immediate: false,
            deep: false
        }],
        val2: [{
            handler: 'onValue2Change',
            immediate: true,
            deep: true
        }]
    }
    
    methods: {
        onVal1Change(newVal, oldVal) {},
        onVal2Change(newVal, oldVal) {}
    }
}

ts写法

import {Vue, Component, Watch} from 'vue-property-decorator';
@Component
export default class MyComponent extends Vue {
    @Watch('val1')
    onVal1Change(newVal, oldVal){}
    
    @Watch('val2', {immediate: true, deep: true})
    onVal2Change(newVal, oldVal){}
}

inject && provide

js写法

import {Vue, Component, Model, Inject} from 'vue-property-decorator'
const symbol = Symbol('baz')

@Component

export default class MyComponent extends Vue {
    inject: {
        foo: 'foo',
        bar: 'bar',
        optional: { from: 'optional', default: 'default' },
        [symbol]: symbol
    },
    
    data() {
        return {
            foo: 'foo',
            baz: 'bar'
        }
    },
    
    provide() {
        return {
            foo: this.foo,
            baz: this.baz
        }
    }
}

ts 写法

import { Component, Inject, Provide, Vue } from 'vue-property-decorator'
 
const symbol = Symbol('baz')
 
@Component
export class MyComponent extends Vue {
  @Inject() readonly foo!: string
  @Inject('bar') readonly bar!: string
  @Inject({ from: 'optional', default: 'default' }) readonly optional!: string
  @Inject(symbol) readonly baz!: string
 
  @Provide() foo = 'foo'
  @Provide('bar') baz = 'bar'
}

@Emit

js写法

export default {
    methods: {
        addNumber(n) {
            this.$emit('eventName', n);
        },
        
        otherEvent(params) {
            this.$emit('other-event', params)
        }
    }
}

ts写法

import {Vue, Component, Emit} from 'vue-property-decorator';
@Component
export default class MyComponent extends Vue {
    @Emit('eventName')
    addNumber(n: Number) {
        return n
    }
    
    @Emit()  // 如果不提供事件名 默认为函数名  驼峰命名会被转化为kebab-case
    otherEvent(params: string) {
        return params
    }

}

计算属性
js写法

export default {
    computed: {
        val: function() {
            ...
            return xx
        }
    }
}

ts写法
// 将该计算属性名定义为一个函数,并在函数前加上get关键字即可

import {Vue, Components} from 'vue-property-decorator'
@Component({})
export default class MyComponent {
    get val() {
        ...
        return xx
    }

}

以上就是vue中引入vue-property-decorator后的常用的一些示例。
日常开发中状态管理工具在各模块数据交互传输也起到很重要的作用,下面介绍下vuex-module-decorator

vuex-module-decorator的使用

state中定义namespace为test的模块

import { VuexModule, Module, Action, Mutation } from 'vuex-module-decorators'

// 待实现的state的接口

export interface TestState {
  num: number,
  firstName: string
}



// 
@Module({namespaced: true, name: 'test', stateFactory: true})

export default class Test extends VuexModule implements TestState {
// state
  public num = 0;
  public firstName = '';

  @Action
  public emitAddOne() {
  // action中调用mutation
    this.addOne();
  }

  @Action
  private emitSubstract() {
    this.substract()
  }

  @Mutation
  private addOne() {
    this.num ++;
  }

  @Mutation
  private substract() {
    this.num --;
  }
  
  // getters
  get addNum() {
    return this.num ++
  }

}

store的使用

import { Vue, Component } from 'vue-property-decorator';
import { getModule } from 'vuex-module-decorator';
import test from '@/store/module/Test';
import store from '@/store/index'

const testModule = getModule(test, store)  // 通过getModule()安全访问Store

@Component({});
export default class MyComponent extends Vue {
    public showStateData(): void {
    // 调用state中的data
        console.log(testModule.num)
    }
    // 调用action
    emitAction():void {
          testModule.emitAddOne()
      }
    // 调用mutation  
      emitMutation(): void {
        testModule.substract()
      }
}

优点和不足
优点挺多:

清晰的函数参数/接口属性,增加了代码可读性和可维护性
静态检查
生成API文档
配合现代编辑器,各种提示
活跃的社区

缺点也有:
和某些库结合的不是很完美(没错,说的就是vue 2.x)

这里提到的vue2.x由于ts先天能力的不足,导致vue的ts语法需要使用class风格(运行时会被转换回原本的vue构造函数的语法),和我们平时熟悉的vue风格有些差异
最后
ts带上vue-property-decorator和vuex-module-decorator,开始愉快的开发吧~

目录
暂无评论,欢迎留下你的评论

运营需要亿点资金维持,您的支持,是小白龙创作的动力!!!

昵称
留言
赞赏金额