項目中往往存在一些數據量較大的接口,當接口加載渲染前台數據時需要很長的時間,此時需要添加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