自定义微调加载程序,用于简单的Vue.js项目

时间:2018-09-27 11:21:08

标签: javascript vue.js

我有一个simple vue project on codesandbox.io,带有vue-router和自定义微调器加载。

Spinner.vue

<template>
  <div class="spinner" v-show="loading">
    <span class="sync" v-bind:style="[spinnerStyle, spinnerDelay1]"></span>
    <span class="sync" v-bind:style="[spinnerStyle, spinnerDelay2]"></span>
    <span class="sync" v-bind:style="[spinnerStyle, spinnerDelay3]"></span>
  </div>
</template>
<script>
export default {
  name: "Spinner",
  props: {
    loading: {
      type: Boolean,
      default: true
    },
    color: {
      type: String,
      default: "#5dc596"
    },
    size: {
      type: String,
      default: "15px"
    },
    margin: {
      type: String,
      default: "2px"
    },
    radius: {
      type: String,
      default: "100%"
    }
  },
  data() {
    return {
      spinnerStyle: {
        backgroundColor: this.color,
        height: this.size,
            width: this.size,
        borderRadius: this.radius,
        margin: this.margin,
        display: 'inline-block',
        animationName: 'spinerAnimation',
        animationDuration: '1.25s',
        animationIterationCount: 'infinite',
        animationTimingFunction: 'ease-in-out',
        animationFillMode: 'both'
      },
      spinnerDelay1: {
        animationDelay: '0.07s'
      },
      spinnerDelay2: {
        animationDelay: '0.14s'
      },
      spinnerDelay3: {
        animationDelay: '0.21s'
      }
    };
  },
  methods: {
    start() {
      this.loading = true;
    },
    end() {
      this.loading = false;
    }
  }
};

</script>

主页是 Home.vue ,其中包含其他组件上的链接:

 <router-link to="/">Home</router-link>
 <router-link to="/helloworld">Hello World</router-link>
 <router-link to="/bigimg">Big Img</router-link>

main.js

import Vue from "vue";
import App from "./App";
import router from "./router";

import Spinner from "./components/Spinner";

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: "#app",
  router,
  components: {
    App,
    Spinner
  },
  template: "<App/>"
});

router.beforeEach((to, from, next) => {
  console.log("next page");
  //loading = true
  next();
});

router.afterEach((to, from) => {
  //setTimeout(() => (loading = false), 1500);
});

在加载主页(Home.vue)并进入子页面项目(组件)时,应该启动Spinner Loader。

问题::当我加载项目的主页(主页)以及转到项目的其他页面时,如何启动加载器?

1 个答案:

答案 0 :(得分:2)

您只需要创建一个状态变量:

const state = {
    loading: false
};

将其注册到您的main.js文件中:

new Vue({
  ...
  data: {
    state
  },
});

在主模板中设置一个条件:

new Vue({
  ...
  template: '<App v-if="!state.loading" /><Spinner v-else/>'
});

然后设置每个路由之前的状态:

router.beforeEach((to, from, next) => {
  console.log("next page");
  state.loading = true;
  setTimeout(() => {
    state.loading = false;
  }, 3000);
  next();
});