vue语法自动转typescript(解放双手)

2020-06-12 21:08:05易采站长站整理

computed

vue官网对于 model的介绍在 computed

以下几种 computed的写法都是正确的


export default {
computed: {
a () { return true },
b: function () { return true },
d: {
get () { return true },
set: function (v) { console.log(v) }
}
}
}

vue-property-decorator并没有提供专门的用于 computed的修饰器,因为 ES6的 get/set语法本身就可以替代 computed
上述转换为 ts对应如下:


export default class YourComponent extends Vue {
get a () { return true }
get b () { return true },
get d (){ return true },
set d (v) { console.log(v) }
}

除此之外,computed其实还支持箭头函数的写法:


export default {
computed: {
e: () => { return true }
}
}

但是 class语法的 get/set不支持箭头函数,所以不好转换,另外因为箭头函数会改变 this的指向,而 computed计算的就是当前 vue实例上的属性,所以一般也不推荐在 computed中使用箭头函数,固然你可以在箭头函数的第一个参数上获得当前 vue实例,但这就未免有点多此一举的嫌疑了,所以我这里略过对箭头函数的处理,只会在遇到 computed上的箭头函数时,给你一个提示

watch

vue官网对于 watch的介绍在watch

以下都是合法的 watch写法:


export default {
watch: {
a: function (val, oldVal) {
console.log('new: %s, old: %s', val, oldVal)
},
// 方法名
b: 'someMethod',
// 该回调会在任何被侦听的对象的 property 改变时被调用,不论其被嵌套多深
c: {
handler: function (val, oldVal) { /* ... */ },
deep: true
},
// 该回调将会在侦听开始之后被立即调用
d: {
handler: 'someMethod',
immediate: true
},
e: [
'handle1',
function handle2 (val, oldVal) { /* ... */ },
{
handler: function handle3 (val, oldVal) { /* ... */ },
immediate: true
}
],
// watch vm.e.f's value: {g: 5}
'e.f': function (val, oldVal) { /* ... */ }
}
}

上述转换为 ts对应如下:


export default class YourComponent extends Vue {
@Watch('a')
onAChanged(val: any, oldVal: any) {}
@Watch('b')
onBChanged (val: any, oldVal: any) {
this.someMethod(val, oldVal)
}
@Watch('c', { deep: true })
onCChanged (val: any, oldVal: any) {}
@Watch('d', { deep: true })
onDChanged (val: any, oldVal: any) {}
@Watch('e')
onE1Changed (val: any, oldVal: any) {}