隐藏无数据模板,直到通过Axios加载数据

时间:2019-05-29 18:26:23

标签: vue.js vuejs2 vue-component

我有一个带有模板部分的典型Vue数据表,如果未找到任何记录,该模板部分会显示警报。问题是,即使我的Axios方法没有机会获得记录,它也会立即显示。

如何在实际数据加载之前防止红色警告消息闪烁?

@Html.TextAreaFor(model => model.DESCRIPTION, 20, 50, htmlAttributes: new { @class = "form-control",@rows="6" })

1 个答案:

答案 0 :(得分:1)

  1. 向数据添加加载状态,并将其设置为true
  2. 设置通话结束时的加载状态(.finally保证)
  3. 在模板中将v-if设置为打开,以显示何时不再加载

请参见下面的代码。

<template>
  <div>
    <v-card>
      <v-card-title>
        <h1>Locations</h1>
      </v-card-title>

      <v-data-table :headers="headers" :items="locations" :search="search" :fixed-header="true" :loading="true" class="elevation-1">
        <template v-slot:items="location">
          <td>{{ location.item.id }}</td>
          <td>{{ location.item.company }}</td>
          <td>{{ location.item.category }}</td>
          <td>{{ location.item.name }}</td>
          <td>{{ location.item.city }}, {{ location.item.state }}</td>
        </template>
        <template v-slot:no-data>
          <v-alert v-if="!loading" :value="true" color="error" icon="warning">Sorry, no locations found.</v-alert>
        </template>
      </v-data-table>
    </v-card>
  </div>
</template>

<script>
import { HTTP } from "@/utils/http-common";

export default {
  name: 'LocationsList',
  data() {
    return {
      headers: [
        { text: "Id", value: "id" },
        { text: "Company", value: "company" },
        { text: "Category", value: "category" },
        { text: "Name", value: "name" },
        { text: "City, State", value: "city" },
      ],
      locations: [],
      errors: [],
      loading: true
    };
  },
  created: function() {
    this.getAllLocations();
  },
  methods: {
    getAllLocations() {
      HTTP.get("locations")
        .then(response => {
          this.locations = response.data;
        })
        .catch(err => {
          this.errors.push(err);
        })
        .finally(() => {
          this.loading = false;
        })
    },
  }
};
</script>