Vue 创建博客前端-DAY2-文章列表

2020-03-02  本文已影响0人  ricekent
服务端支持跨域

nest 项目 main.ts 中加入 app.enableCors()

使用 axios 接收服务端数据
  1. main.ts 中创建 axios实例http
const http = axios.create({
  baseURL: process.env.VUE_APP_API_URL
});

Vue.prototype.$httpajax = http;
Vue.prototype.$http = http;

  1. 全局声明 http
# 在 src 目录下创建 custom-vue.d.ts 文件
import Vue from 'vue'
import { AxiosInstance } from 'axios'

declare module 'vue/types/vue' {
    interface Vue {
      $http: AxiosInstance
    }
  }
  1. 配置 nest 端口环境变量与前端相同。
制作列表页面
  1. views目录下创建Main.vue文件。使用vuetify卡片展示文章目录。
  2. router/index.ts 中,将Main.vue放置于根路由上。
import Main from "../views/Main.vue";
const routes = [
  {
    path: "/",
    name: "Home",
    component: Main
  },
]
  1. 编写 Main.vue 中的 js
import { Vue, Component } from "vue-property-decorator";

@Component({})
export default class PostList extends Vue {
  article = {};

  // 展示 10 篇文章
  query = {
    limit: 10
  };

  // 转换默认的 mongodb 日期格式
  formatDate(date: string): string {
    return date.split(".")[0].replace("T", " ");
  }

  async fetch() {
    const res = await this.$http.get(`posts`, {
      params: {
        query: this.query
      }
    });
    this.article = res.data;
  }

  created() {
    this.fetch();
  }
}

上一篇下一篇

猜你喜欢

热点阅读