当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue2实现数据请求显示loading图

vue2实现数据请求显示loading图

2017年12月08日  | 移动技术网IT编程  | 我要评论
一般项目中,有时候会要求,你在数据请求的时候显示一张gif图片,然后数据加载完后,消失。这个,一般只需要在封装的axios中写入js事件即可。当然,我们首先需要在app.v

一般项目中,有时候会要求,你在数据请求的时候显示一张gif图片,然后数据加载完后,消失。这个,一般只需要在封装的axios中写入js事件即可。当然,我们首先需要在app.vue中,加入此图片。如下:

<template>
 <div id="app">
 <loading v-show="fetchloading"></loading>
 <router-view></router-view>
 </div>
</template>

<script>
 import { mapgetters } from 'vuex';
 import loading from './components/common/loading';

 export default {
 name: 'app',
 data() {
 return {
 }
 },
 computed: {
 ...mapgetters([
 'fetchloading',
 ]),
 },
 components: {
 loading,
 }
 }
</script>

<style>
 #app{
 width: 100%;
 height: 100%;
 }
</style>

这里的fetchloading是存在vuex里面的一个变量。在store/modules/common.js里需要如下定义:

/* 此js文件用于存储公用的vuex状态 */
import api from './../../fetch/api'
import * as types from './../types.js'
const state = {
 // 请求数据时加载状态loading
 fetchloading: false
}
const getters = {
 // 请求数据时加载状态
 fetchloading: state => state.fetchloading
}
const actions = {
 // 请求数据时状态loading
 fetch_loading({
 commit
 }, res) {
 commit(types.fetch_loading, res)
 },
}
const mutations = {
 // 请求数据时loading
 [types.fetch_loading] (state, res) {
 state.fetchloading = res
 }
}

loading组件如下:

<template>
 <div class="loading">
 <img src="./../../assets/main/running.gif" alt="">
 </div>
</template>

<script>
 export default {
 name: 'loading',
 data () {
 return {}
 },
 }
</script>
<!-- add "scoped" attribute to limit css to this component only -->
<style scoped>
 .loading{
 position: fixed;
 top:0;
 left:0;
 z-index:121;
 width: 100%;
 height: 100%;
 background: rgba(0,0,0,0.3);
 display: table-cell;
 vertical-align: middle;
 text-align: center;
 }
 .loading img{
 margin:5rem auto;
 }
</style>

最后在fetch/api.js里封装的axios里写入判断loading事件即可:如下

// axios的请求时间
let axiosdate = new date()
export function fetch (url, params) {
 return new promise((resolve, reject) => {
 axios.post(url, params)
 .then(response => {
 // 关闭 loading图片消失
 let odate = new date()
 let time = odate.gettime() - axiosdate.gettime()
 if (time < 500) time = 500
 settimeout(() => {
  store.dispatch('fetch_loading', false)
 }, time)
 resolve(response.data)
 })
 .catch((error) => {
 // 关闭 loading图片消失
 store.dispatch('fetch_loading', false)
 axiosdate = new date()
 reject(error)
 })
 })
}
export default {
 // 组件中公共页面请求函数
 commonapi (url, params) {
 if(stringquery(window.location.href)) {
 store.dispatch('fetch_loading', true);
 }
 axiosdate = new date();
 return fetch(url, params);
 }
}

这样就实现了,项目中当加载数据的时候,显示gif图片,当数据加载出来时消失。

关于vue.js的学习教程,请大家点击专题vue.js组件学习教程vue.js前端组件学习教程进行学习。

更多vue学习教程请阅读专题《vue实战教程》

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网