项目中往往存在一些数据量较大的接口,当接口加载渲染前台数据时需要很长的时间,此时需要添加loading来提醒用户页面正在加载中。
以下是添加loading的步骤:
1. 一般情况来说,loading作为全局加载状态应该写在App.vue中
<template> <div id="app"> <router-view></router-view> <van-loading v-if="isShow" size="24px" vertical>加载中...</van-loading> //我用的是Vant组件库 </div> </template>
isShow控制loading组件的显隐,因此在请求接口前将isShow置为true,接口加载完成后将isShow置为false即可。
2. 参考官方方法引入vuex,在src下创建一个store文件夹,并新增js文件
(由于loading组件在App.vue中,每次更改时很麻烦,所以推荐使用vuex)
const store = new Vuex.Store({ state: { isShow: false, //加载时的loading }, mutations: { // 展示loading showLoading(state) { state.isShow = true; }, // 关闭loading hideLoading(state) { state.isShow = false; }, }, });
3. 在main.js 中引入store.js,并挂载到 Vue 实例上
import store from './store'; new Vue({ el: '#app', components: { App }, router, // 注入路由 store, //全局状态管理 template: '<App />', });
4. 在需要用到的地方通过this.$store.commit()改变isShow的状态
(1)全局(http.js)
axios.interceptors.response.use( function(response) { store.commit('showLoading') let resData = response.data; // 以下无数据的判断对取号接口适配 if (!resData) { store.commit('hideLoading') return Promise.reject('数据格式不对', response); } if (resData.code === 200 || resData.code === '200') { store.commit('hideLoading') return resData; } else { store.commit('hideLoading') return Promise.reject(resData.message); } }, );
(2)局部
getData() { this.$store.commit('showLoading'); this.$http .get(this.$url.get('xxxxxxxx'), { queryNum: 2 }) .then(res => { if (res.code === 200) { this.$store.commit('hideLoading'); this.contentList = res.data; } }); },
总结:在请求时this.$store.commit('showLoading'),在请求完成后this.$store.commit('hideLoading')
5. 修改App.vue文件,监听isShow的值的变化
<script> import { mapState } from 'vuex'; export default { name: 'App', computed: { ...mapState(['isShow']), }, }; </script>
以上为自己项目实践内容,参考资料总结了此篇笔记。
参考资料地址:https://blog.csdn.net/starleejay/article/details/80738296 | https://segmentfault.com/a/1190000023647450