【问题标题】:Why is my false conditional element fickering while route is loading?为什么我的错误条件元素在路由加载时闪烁?
【发布时间】:2020-01-30 21:38:18
【问题描述】:

背景:我有一个页面根据 Axios 响应显示不同的 div。如果 Axios Get 请求返回 不 填充数据数组 myExpense[] 的响应,它会显示带有警报警告类的 div。否则,如果响应确实填充了数组,它会显示带有 alert-succes 类的 div。 代码如下:

<template>
  <div class="profilePage">
    <div class="container">

      <div class="row">

        <div class="col" v-if="Array.isArray(myExpense)
       && myExpense == 0"><!--Warning div-->
          <p class="alert alert-warning">You do not have a budget at the moment</p>
          <router-link to="/budgetform" tag="button" class="btn btn-primary mt-5">Create Budget</router-link>
        </div>

        <div v-else class="col-md-12 alert alert-success"><!--Success div-->
          <p class="yourBalance">
            Your monthly balance
            <br />
            <span>${{myExpense[0].earnings}}</span>
          </p>
          <router-link to="/mybudget" tag="button" class="btn btn-primary mt-5">My budget</router-link>
        </div>
      </div>
      <div class="row">
        <div class="col-md-12">
          <a href="http://localhost:3000/auth/logout" class="btn btn-primary">Logout</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "userProfile",
  data() {
    return {
      myExpense: [],//This array to be populated by axios response
         };
  },
  methods: {},
  created() {
    axios
      .get("http://localhost:3000/budget", {
        headers: { "Content-Type": "application/json" },
        withCredentials: true
      })
      .then(res => {
        if (res.data.name == undefined) {
          this.$router.push("/");
        }
        this.profile = res.data;
        this.myExpense = res.data.budget;
      });
  }
};
</script>

问题:

每当这个页面被渲染时,假的 div 会在根据条件显示正确的 div 之前闪烁。此外,有时它也会显示空白。

我尝试添加 v-cloak,但这似乎不是问题。

提前感谢您的帮助

【问题讨论】:

  • “假 div”是 v-else div 吗? @EddieWeldon
  • 这取决于是否填充了 myExpense 属性。但是,无论状态如何,警告 div 或 v-if 语句在加载过​​程中总是闪烁
  • 它可能会闪烁,因为 myExpense 正在“正在填充”。尝试重新安排您的布尔逻辑,以便 v-if 语句首先检查 myExpense 是否为空,然后检查 myExpense 的实际值/类型

标签: javascript vue.js axios


【解决方案1】:

我能够找出问题所在。获取请求检索数据的速度不如呈现页面的速度。所以我不得不在组件渲染之前使用 beforeRouteEnter 来检索数据

像这样:

beforeRouteEnter(to, from, next) {
    axios
      .get("http://localhost:3000/budget", {
        headers: { "Content-Type": "application/json" },
        withCredentials: true
      })
      .then(res => {
        next(vm => {
          vm.userName = res.data.name;
          vm.myExpenses = res.data.budget[0].expenses;
          vm.earnings = res.data.budget[0].earnings;
        });
      })
      .catch(err => {
        next(vm => {
          vm.err = err;
        });
      });
  }

【讨论】:

    猜你喜欢
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2013-05-26
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多