项目中loading效果的实现(主要用了iview-admin)~

做一个全局的loading,放在拦截器中,这样就不用修改其他的代码或者vue中的引入。

第一步:在src/store/modules/app.js

state里面定义一个全局的loading属性,并初始化,例如:

isGlobalSpin: false, // 全局Loading

在mutations里面定义去改变这个属性的函数,例如:

 changeGlobalSpin (state, show) {
            state.isGlobalSpin = show;
        },

第二步:在src/views/Main.vue里面添加iview中的loading组件,加到<template><div>里面,并自定义样式等。例如


<Spin fix v-if="spinShow">
            <Icon type="load-c" size=18 class="demo-spin-icon-load"></Icon>
            <div>Loading</div>
        </Spin>

我直接用的官网的样式

.demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }

然后定义spinShow函数决定是否显示loading,写在computed里面

spinShow () {
                return this.$store.state.app.isGlobalSpin;
            }

第三步:添加拦截器,本来iview-admin中有一个axios.js(src/libs/axios.js),想着直接在这里面的拦截器里去写,但是报错,还没有找到怎么处理BUG;只能先放在main.js(src/main.js)里面新添加一个拦截器来实现。

别忘了引入axios

import axios from 'axios'

拦截器:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    store.commit('changeGlobalSpin', true);
    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    store.commit('changeGlobalSpin', false);
    return response;
}, function (error) {
    // Do something with response error
    return Promise.reject(error);
});


最后一步:使用,直接在需要用到请求的页面引入axios

import axios from 'axios'

// get同样适用
axios.post("#", {}).then(function(response){console.log(response)}).catch(function(error){console.log(error)})

猜你喜欢

转载自my.oschina.net/yj1993/blog/1809037
今日推荐