如何在vue 3合成API中显示加载gif

Ang*_*gel 2 vue.js vue-composition-api

我对 vue 很陌生。我想做的是在等待端点返回时加载 gif。

我正在尝试使用 watchEffect,但我无法弄清楚。如果这是正确的方法我该怎么做?如果不是我应该用什么代替?

谢谢

编辑:代码

<template>
    <div class="player-list" :key="playerList.id" v-for="playerList in players.playerLists">
        <PlayerList :playerList="playerList" />
    </div>
</template>

<script>
import getPlayers from "@/composables/getPlayers";
import PlayerList from "@/components/PlayerList";
import { watchEffect } from 'vue';

export default {
    name: 'PlayerLists',
    components: {
        PlayerList
    },
    setup() {

        const { players, error, load } = getPlayers() //request endpoint
        load()

        watchEffect(() => {
            console.log('watch effect function')
        })

        return { players, error }
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

mat*_*own 8

Vue 应用程序应该是数据驱动的。因此,不要依赖效果,而是通过设置数据来改变应用程序的外观。如果您从端点获取一些数据,则可以安全地假设您将其放置在应用程序中的某个位置以显示它,例如Ref.

那么,只要您的Ref数据不是它正在等待成为的数据,为什么不显示您的加载微调器呢?即,显示 GIF,同时someRef == null?

<template>
  <img v-if="data === null" src="./img/loading.gif" alt="Loading" />
  <div v-else>
    <div>Here's the data!</div>
    <pre>{{ data.toString() }}</pre>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const data = ref(null);

    onMounted(() => {
      // Replace this `fetch` call with whatever your endpoint call may be.
      fetch('./endpoint')
        .then(resp => resp.json())
        .then(json => data.value = json);
    });

    return { data };
  }
};
</script>
Run Code Online (Sandbox Code Playgroud)

那有意义吗?您的应用程序应该对您的数据进行建模。您可以利用“加载 GIF 只应在我们没有数据时显示”这一事实,嗯...只要未设置数据就显示 GIF。

  • 是的,这很有意义并且有效!谢谢马修 (2认同)