APP.vue
<template> <div id="app"> <loading v-if='loading'></loading> <router-view/> </div> </template> <script> import { mapState } from "vuex"; import Loading from "./components/loading"; import "./assets/css/reset.css"; export default { name: "App", data() { return { }; }, mounted() { }, computed:{ ...mapState([ 'loading' ]) }, components: { Loading } }; </script>
loading.vue 組件
<template> <div class="loading"> <img src="../assets/img/image/loading.gif"> </div> </template> <script> export default { name: "loading", data() { return {}; }, methods:{ } }; </script> <style> .loading { position: fixed; top: 0; left: 0; z-index: 121; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.3); display: flex; align-items: center; justify-content: center; } .loading img { margin: 5rem auto; width: 200px; z-index: 999; } </style>
vuex中store.js
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const state = { loading: false // 請求數據時加載狀態loading } const getters = { } const actions = { } const mutations = { // 請求數據時loading showLoading(state){ state.loading = true }, hideLoading (state) { state.loading = false } } export default new Vuex.Store({ state, getters, actions, mutations });
http.js (公用的請求數據)
/* 接口處理函數 這個函數每個項目都是不一樣的,我現在調整的是適用於 https://cnodejs.org/api/v1 的接口,如果是其他接口 需要根據接口的參數進行調整。參考說明文檔地址: https://cnodejs.org/topic/5378720ed6e2d16149fa16bd 主要是,不同的接口的成功標識和失敗提示是不一致的。 另外,不同的項目的處理方法也是不一致的,這里出錯就是簡單的alert */ function apiAxios (method, url, params, success, failure,error) { url_check() store.commit('showLoading') /**loading請求**/ axios({ method: method, url: url, data: method === 'POST' || method === 'PUT' ? params : null, params: method === 'GET' || method === 'DELETE' ? params : null, baseURL: root, withCredentials: true, headers:{ 'token':store.state.token } }) .then(function (res) { console.log(res.data); if(res.data.code== 0) { if (success) { store.commit('hideLoading') /**請求成功后取消loading狀態**/ success(res.data) console.log(res.data); } }else if(res.data.code=='800202'){ alert('身份已過期,請重新登錄!') window.location.href = "/login"; }else if(res.data.code=='800203'){ alert('您的帳號已在其他設備登陸,請重新登錄!') window.location.href = "/login"; }else{ if (failure) { failure(res.data) }else{ console.log('error: ' + JSON.stringify(res.data)) } } }) .catch(function (err) { if(error){ error(err) } }) }
-------END