【问题标题】:Show spinner (preloader/loading indicator) whenever page changes and hide when all assets are loaded in Vue Gridsome每当页面更改时显示微调器(预加载器/加载指示器)并在 Vue Gridsome 中加载所有资产时隐藏
【发布时间】:2020-11-26 05:09:17
【问题描述】:

我正在使用 Gridsome(带有 Vue 路由器的 Vue 静态站点生成器),并且我在 index.html 中创建了一个预加载器,它是一个涵盖所有内容的简单 div。在 index.html 中,我还添加了这个 JS 代码以在加载所有内容时隐藏预加载器

window.onload = function() {
  document.getElementById('preloader').style.display = 'none';
};

这仅适用于初始加载,但在更改页面时我无法显示它并再次隐藏它。

我已尝试将此添加到我的 Layout 组件的 beforeDestroy() 钩子以再次显示预加载器

beforeDestroy() {
  this.preloader.style.display = 'block';
}

当路线改变时显示成功,但是如果我像这样在mounted()中添加隐藏逻辑

mounted() {
  this.preloader.style.display = 'none';
}

从一开始就不会显示预加载器。

我无法找到有关此类加载指示器的任何资源,我只能找到用于异步调用的资源,例如 axiosfetch。我之前在静态 HTML 文件中创建过预加载器,但从未在 SPA 中创建过。有人可以将我推向正确的方向吗?即使是谷歌搜索关键字也会有所帮助

【问题讨论】:

  • 用vuex怎么样? Client API \- Gridsome
  • @nabeen 你能详细说明这个想法吗?
  • 我展示了 vuex 示例代码。看看

标签: vue.js vue-router gridsome


【解决方案1】:

在这种情况下你可以使用 vuex。

首先,添加您的状态src/main.js

import DefaultLayout from "~/layouts/Default.vue";
import Vuex from "vuex";

export default function(Vue, { appOptions }) {
  Vue.component("Layout", DefaultLayout);
  Vue.use(Vuex);

  appOptions.store = new Vuex.Store({
    state: {
      loading: false,
    },
    mutations: {
      on(state) {
        state.loading = true;
      },
      off(state) {
        state.loading = false;
      },
    },
  });
}

其次,将微调器添加到./src/layouts/Default.vue

<template>
  <div class="layout">
    // add your spinner here or another
    <div v-if="$store.state.loading">loading</div>
    <slot />
  </div>
</template>

最后,添加提交代码页、模板或组件。如下所示。

<script>
export default {
  created() {
    // commit("on") first
    this.$store.commit("on");

    // commit("off") last, after fetch data or more.
    this.$store.commit("off");
  },
};
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-10
    • 2021-01-16
    • 1970-01-01
    • 2014-03-17
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多