Vue 与 TypeScript
Typescript 的本质
本质:Typescript 检查类型的 JavaScript 的版本
编译报错:提示代码错误,更加严谨(实际也能编译)
可以配置为有错误即无法编译
compilerOptions:{
"noEmitOnError":true
}
优点
- 自动提示更智能
- 相关严谨,不能随意写代码,编译时就会报错。
- 类型检查:无法点出错误的属性
Vue 单文件组件
// 1. 使用 JS 对象
export default { data, props, methods, creater, ...}
// 2. 使用 TS 类
@Component
export default class Page extends Vue{
text : string;
@Prop(String) text: string | undefined;
/*
@Prop 告诉 Vue 不是 data,而是 prop 属性
String 为字符串,text为外部变量
":" 后面是 Typescript 的编译时类型
*/
}
// 3. 使用 JS 类,与 TS 相似,只是不需要类型检查。
外部数据只读属性
export default class Tags extends Vue {
@Prop()
readonly dataSource: string[] | undefined;
}
修饰符的原理
使用修饰符 .sync 实现数据传参,写代码啦教程
规则
- 组件不能修改 props 外部数据
$emit可以发出事件,并传参(发布订阅模式)$event可以获取$emit的参数
参考:
关闭 vue-cli-service lint
删除 package.json 里面其中一个选项即可。
"gitHooks": {
"pre-commit": "lint-staged"
},
或者 git commit后面加上 --no-verify
Number 的困难
- 外部的值无法被内部所修改,存在两个默认值
即使通过导入值,由于存在 number 和 string 之间的类型切换,导致出错
export default class NumberPad extends Vue {
@Prop() readonly value: number
output = this.value.toString()
}
创建成功与失败的返回值
TS 的联合类型
type TagListModel = {
data: string[]
fetch: () => string[]
// 联合类型
create: (name: string) => 'success' | 'duplicated'
save: () => void
}
使用 Vue Router 实现
通过钩子来获取数据
{
path: '/labels/edit/:id',
component: EditLabel
},
created() {
const id = this.$route.params;
console.log(id);
}
Vue 生命周期
<script>
export default {
beforeCreate() {
console.log("beforeCreate")
},
created() {
console.log("created")
},
beforeMount() {
console.log("beforeMount")
},
mounted() {
console.log("mounted")
},
beforeUpdate() {
console.log("beforeUpdate")
},
updated() {
console.log("updated")
},
beforeDestroy() {
console.log("beforeDestroy")
},
destroyed() {
console.log("destroyed")
}
}
</script>
Component 的不同
// lang='ts'
@Component({
components: {
VChart
}
})
// lang='js'