// api/main.ts import request from '../utils/request'; // get export function getSomeThings(params:any) { return request({ url: '/api/getSomethings', }); } // post export function postSomeThings(params:any) { return request({ url: '/api/postSomethings', methods: 'post', data: params }); }
5. 编写一个组件
为了减少时间,我们来替换掉 src/components/HelloWorld.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 { Component, Prop, Vue } from 'vue-property-decorator'; // 在这里对数据进行类型约束 export interface Post { title: string; body: string; author: string; datePosted: Date; } @Component export default class HelloWorld extends Vue { @Prop() private post!: Post; get date() { return `${this.post.datePosted.getDate()}/${this.post.datePosted.getMonth()}/${this.post.datePosted.getFullYear()}`; } } </script> <style scoped> h2 { text-decoration: underline; } p.meta { font-style: italic; } </style>
然后在 Home.vue 中使用:
<template> <div> <img alt="Vue logo" src="https://www.jb51.net/assets/logo.png"> <HelloWorld v-for="blogPost in blogPosts" :post="blogPost" :key="blogPost.title" /> </div> </template> <script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; import HelloWorld, { Post } from '@/components/HelloWorld.vue'; // @ is an alias to /src @Component({ components: { HelloWorld, }, }) export default class Home extends Vue { private blogPosts: Post[] = [ { title: 'My first blogpost ever!', body: 'Lorem ipsum dolor sit amet.', author: 'Elke', datePosted: new Date(2019, 1, 18), }, { title: 'Look I am blogging!', body: 'Hurray for me, this is my second post!', author: 'Elke', datePosted: new Date(2019, 1, 19), }, { title: 'Another one?!', body: 'Another one!', author: 'Elke', datePosted: new Date(2019, 1, 20), }, ]; } </script>
这时候运行项目:
这就是简单的父子组件