ts02
2020-06-06 本文已影响0人
MickeyMcneil
插件
ts-node:编译 + 运行。
泛型正向
泛型:创建可重用的组件,一个组件可支持多种类型的数据。
项目结构
-
shims-tsx.d.ts
,允许编写jsx
代码,在.tsx
结尾的文件中 -
shims-vue.d.ts
,让ts
识别vue
文件
interface
和 type
的区别
相同点:都用来描述对象或函数,都能拓展(extends
)
不同点:
type
可声明基本类型别名,联合类型,元组。type
可用typeof
获取实例的类型进行赋值。
interface
可以声明合并。interface
有可选属性和只读属性。
private
、public
、protected
vue组件的ts写法
Vue.extend
需要与mixins
结合使用。
vue-class-component
:基于类的API,官方在维护。
vue-property-decorator
:基于vue-class-component
,写起来更顺手。
子组件components/Blog.vue
<template>
<div>
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
<p>written by {{ post.author }} on {{ date }}</p>
</div>
</template>
<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
// 对数据进行类型约束
export interface Post {
title: string;
body: string;
author: string;
datePosted: Date;
}
@Component
export default class Blog extends Vue {
@Prop() private post!: Post;
get date() {
return `${this.post.datePosted.getDate()}/${this.post.datePosted.getMonth()}/${this.post.datePosted.getFullYear()}`;
}
}
</script>
<style lang="scss" scoped></style>
父组件home.vue
<template>
<div class="about">
<h1>This is an about page</h1>
<Blog v-for="item in data" :post="item" :key="item.author"></Blog>
</div>
</template>
<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";
import Blog, { Post } from "@/components/Blog.vue";
@Component({
components: {
Blog,
}
})
export default class Home extends Vue{
private data: Post[] = [
{
title: '我来了!!!',
body: '这是我的第一篇博客',
author: 'leeee',
datePosted: new Date(2020, 6, 6)
},
{
title: '今天放假了',
body: '这是我的第二篇博客',
author: 'yyyyy',
datePosted: new Date(2020, 6, 8)
},
{
title: '要开始运动了',
body: '这是我的第三篇博客',
author: 'gggeee',
datePosted: new Date(2020, 6, 10)
},
]
}
</script>
es6中的class
创建getter
时,使用关键字get