ts02

作者: MickeyMcneil | 来源:发表于2020-06-06 15:31 被阅读0次

ref从零实现,主要跟着这篇文章来练习的

插件

ts-node:编译 + 运行。

泛型正向

泛型:创建可重用的组件,一个组件可支持多种类型的数据。


ts练习,文章来源

项目结构

  1. shims-tsx.d.ts,允许编写jsx代码,在.tsx结尾的文件中
  2. shims-vue.d.ts,让ts识别vue文件

interfacetype的区别

相同点:都用来描述对象或函数,都能拓展(extends)

不同点:
type可声明基本类型别名,联合类型,元组。type可用typeof获取实例的类型进行赋值。
interface可以声明合并。interface有可选属性和只读属性。

privatepublicprotected

vue组件的ts写法

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


拓展:es6中class的用法

相关文章

  • ts02

    ref从零实现,主要跟着这篇文章来练习的 插件 ts-node:编译 + 运行。 泛型正向 泛型:创建可重用的组件...

网友评论

      本文标题:ts02

      本文链接:https://www.haomeiwen.com/subject/annxtktx.html