**Vue.extend **
import Vue from 'vue' const Component = Vue.extend({
// type inference enabled
})
vue-class-component
import { Component, Vue, Prop } from 'vue-property-decorator'@Component
export default class Test extends Vue {
@Prop({ type: Object })
private test: { value: string }
}
理想情况下,
Vue.extend 的书写方式,是学习成本最低的。在现有写法的基础上,几乎 0 成本的迁移。但是
Vue.extend 模式,需要与
mixins 结合使用。在 mixin 中定义的方法,不会被 typescript 识别到,这就意味着会出现 丢失代码提示、类型检查、编译报错等问题。
菜鸟才做选择,大佬都挑最好的。直接讲第二种吧:
4.1
vue-class-component我们回到
src/components/HelloWorld.vue
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<!-- 省略 -->
</div>
</template><script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
@Component
export default class HelloWorld extends Vue {
@Prop() private msg!: string;
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>
有写过
python 的同学应该会发现似曾相识:
vue-property-decorator 这个官方支持的库里,提供了函数 **装饰器(修饰符)**语法1. 函数修饰符
@“@”,与其说是修饰函数倒不如说是引用、调用它修饰的函数。
或者用句大白话描述:
@ : “下面的被我包围了。”举个栗子,下面的一段代码,里面两个函数,没有被调用,也会有输出结果:
test(f){
console.log("before ...");
f()
console.log("after ...");
}@test
func(){
console.log("func was called");
}
直接运行,输出结果:
before …
func was called
after …
上面代码可以看出来:
只定义了两个函数:
test 和
func ,没有调用它们。如果没有“@test”,运行应该是没有任何输出的。










