如何在Vue + TypeScript中渲染之前等待组件中的数据

时间:2019-10-14 16:38:19

标签: typescript vue.js vue-router

在第一个组件中,我使用路由器打开新页面
Component_1.vue:

let route = this.$router.resolve({ name: 'Schedule', params : { id: (this.schedule[0].schedule_id).toString() } });
window.open(route.href, '_blank');

router.ts:

import Vue from "vue";
import Router from "vue-router";
import SchedulePage from "./views/SchedulePage.vue"

Vue.use(Router);

export default new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      // here is other routes
    },
    {
      path: "/schedule/:id",
      name: "Schedule",
      component: SchedulePage,
    },
  ]
});

SchedulePage.vue

此组件在schedule从异步函数获取之前呈现。 如何解决这个问题呢?是的,我读了this question,但我不明白如何存储和返回created()getSchedule()的诺言

<template>
  <schedule-table
    v-if = "schedule.length > 0"
    :exercises="schedule.exercises"
  />
</template>

<script lang="ts">
import store from "@/store"

import Vue from 'vue';
import ScheduleTable from '../components/ScheduleTable.vue';
import Component from 'vue-class-component';
import { ISchedule }  from "@/interfaces";
import * as api from '@/api';


export default Vue.extend({
  components: {
    ScheduleTable,
  },

  data(){
    return {
      schedule : {}
    }
  },
  methods: {
    getSchedule : async function () {
      this.schedule = await api.getScheduleById( this.$route.params.id );
    }
  },
  async created(){
    await this.getSchedule();
  }

});
</script>

1 个答案:

答案 0 :(得分:0)

感谢山丘

我错了
<schedule-table
    v-if = "schedule.length > 0"
    :exercises="schedule.exercises"
/>

schedule不是数组,而是对象。 最好使用这样的东西

object.entries(schedule).length != 0

More info about testing objects for emptiness here