vue項(xiàng)目及axios請求獲取數(shù)據(jù)方式
一般vue項(xiàng)目中 一個頁面是由多個組件組成的,各個組建的數(shù)據(jù)都是統(tǒng)一在主界面的組件中發(fā)送axios請求獲取,這樣極大地提高了性能。
一、首先導(dǎo)入用到的組件和axios
import HomeHeader from './components/Header' import HomeSwiper from './components/Swiper' import HomeIcons from './components/Icons' import HomeRecommend from './components/Recommend' import HomeWeekend from './components/Weekend' import axios from 'axios' export default { ? name: 'Home', ? components: { ? ? HomeHeader, ? ? HomeSwiper, ? ? HomeIcons, ? ? HomeRecommend, ? ? HomeWeekend ? },
二、在data中將要用到的數(shù)據(jù)給一個初始值,為空
? data () { ? ? return { ? ? ? swiperList: [], ? ? ? iconList: [], ? ? ? recommendList: [], ? ? ? weekendList: [] ? ? } ? },
三、在methods中寫方法,發(fā)送axios獲取數(shù)據(jù)
methods: { ? ? getHomeInfo () { ? ? ? axios.get('/api/index.json') ? ? ? ? .then(this.getHomeInfoSucc) ? ? }, ? ? getHomeInfoSucc (res) { ? ? ? res=res.data ? ? ? if (res.ret && res.data) { ? ? ? ? const data = res.data ? ? ? ? this.swiperList = data.swiperList ? ? ? ? this.iconList = data.iconList ? ? ? ? this.recommendList = data.recommendList ? ? ? ? this.weekendList = data.weekendList ? ? ? } ? ? } ? }, ? mounted () { ? ? this.getHomeInfo() ? } }
四、傳遞數(shù)據(jù)
<div> ? <home-header></home-header> ? <home-swiper :list="swiperList"></home-swiper> ? <home-icons :list="iconList"></home-icons> ? <home-recommend :list="recommendList"></home-recommend> ? <home-weekend :list="weekendList"></home-weekend> </div>
五、封裝 axios
通過簡單的配置就可以本地調(diào)試線上環(huán)境, 這里結(jié)合業(yè)務(wù)封裝了axios 。
import axios from 'axios' import { Message } from 'element-ui' import store from '@/store' import { getToken } from '@/utils/auth' // 創(chuàng)建axios實(shí)例 const service = axios.create({ ? baseURL: process.env.BASE_API, // api的base_url ? timeout: 5000 // 請求超時時間 }) // request攔截器 service.interceptors.request.use(config => { ? // Do something before request is sent ? if (store.getters.token) { ? ? config.headers['X-Token'] = getToken() // 讓每個請求攜帶token--['X-Token']為自定義key 請根據(jù)實(shí)際情況自行修改 ? } ? return config }, error => { ? // Do something with request error ? console.log(error) // for debug ? Promise.reject(error) }) // respone攔截器 service.interceptors.response.use( ? response => response, ? /** ? * 下面的注釋為通過response自定義code來標(biāo)示請求狀態(tài),當(dāng)code返回如下情況為權(quán)限有問題,登出并返回到登錄頁 ? * 如通過xmlhttprequest 狀態(tài)碼標(biāo)識 邏輯可寫在下面error中 ? */ ? // ?const res = response.data; ? // ? ? if (res.code !== 20000) { ? // ? ? ? Message({ ? // ? ? ? ? message: res.message, ? // ? ? ? ? type: 'error', ? // ? ? ? ? duration: 5 * 1000 ? // ? ? ? }); ? // ? ? ? // 50008:非法的token; 50012:其他客戶端登錄了; ?50014:Token 過期了; ? // ? ? ? if (res.code === 50008 || res.code === 50012 || res.code === 50014) { ? // ? ? ? ? MessageBox.confirm('你已被登出,可以取消繼續(xù)留在該頁面,或者重新登錄', '確定登出', { ? // ? ? ? ? ? confirmButtonText: '重新登錄', ? // ? ? ? ? ? cancelButtonText: '取消', ? // ? ? ? ? ? type: 'warning' ? // ? ? ? ? }).then(() => { ? // ? ? ? ? ? store.dispatch('FedLogOut').then(() => { ? // ? ? ? ? ? ? location.reload();// 為了重新實(shí)例化vue-router對象 避免bug ? // ? ? ? ? ? }); ? // ? ? ? ? }) ? // ? ? ? } ? // ? ? ? return Promise.reject('error'); ? // ? ? } else { ? // ? ? ? return response.data; ? // ? ? } ? error => { ? ? console.log('err' + error)// for debug ? ? Message({ ? ? ? message: error.message, ? ? ? type: 'error', ? ? ? duration: 5 * 1000 ? ? }) ? ? return Promise.reject(error) ? }) export default service
使用
import request from '@/utils/request' export function getInfo(params) { ? return request({ ? ? url: '/user/info', ? ? method: 'get', ? ? params ? }); }
后臺項(xiàng)目每個請求都是要帶 token 來驗(yàn)證權(quán)限的,封裝之后就不用每個請求都手動來塞 token,或者來做一些統(tǒng)一的異常處理,一勞永逸。
而且因?yàn)閍pi 是根據(jù) env 環(huán)境變量動態(tài)切換的,如果以后線上出現(xiàn)了bug,我們只需配置一下 @/config/dev.env.js 再重啟一下服務(wù),就能在本地模擬線上的環(huán)境了。
module.exports = { ? ? NODE_ENV: '"development"', ? ? BASE_API: '"https://api-dev"', //修改為'"https://api-prod"'就行了 ? ? APP_ORIGIN: '"https://xxx.com"'? }
axios攔截器
通過request攔截器在每個請求頭里面塞入token,好讓后端對請求進(jìn)行權(quán)限驗(yàn)證。
創(chuàng)建一個respone攔截器,當(dāng)服務(wù)端返回特殊的狀態(tài)碼,我們統(tǒng)一做處理,如沒權(quán)限或者token失效等操作。
import axios from 'axios' import { Message } from 'element-ui' import store from '@/store' import { getToken } from '@/utils/auth' // 創(chuàng)建axios實(shí)例 const service = axios.create({ ? baseURL: process.env.BASE_API, // api的base_url ? timeout: 5000 // 請求超時時間 }) // request攔截器 service.interceptors.request.use(config => { ? // Do something before request is sent ? if (store.getters.token) { ? ? config.headers['X-Token'] = getToken() // 讓每個請求攜帶token--['X-Token']為自定義key 請根據(jù)實(shí)際情況自行修改 ? } ? return config }, error => { ? // Do something with request error ? console.log(error) // for debug ? Promise.reject(error) }) // respone攔截器 service.interceptors.response.use( ? response => response, ? /** ? * 下面的注釋為通過response自定義code來標(biāo)示請求狀態(tài),當(dāng)code返回如下情況為權(quán)限有問題,登出并返回到登錄頁 ? * 如通過xmlhttprequest 狀態(tài)碼標(biāo)識 邏輯可寫在下面error中 ? */ ? // ?const res = response.data; ? // ? ? if (res.code !== 20000) { ? // ? ? ? Message({ ? // ? ? ? ? message: res.message, ? // ? ? ? ? type: 'error', ? // ? ? ? ? duration: 5 * 1000 ? // ? ? ? }); ? // ? ? ? // 50008:非法的token; 50012:其他客戶端登錄了; ?50014:Token 過期了; ? // ? ? ? if (res.code === 50008 || res.code === 50012 || res.code === 50014) { ? // ? ? ? ? MessageBox.confirm('你已被登出,可以取消繼續(xù)留在該頁面,或者重新登錄', '確定登出', { ? // ? ? ? ? ? confirmButtonText: '重新登錄', ? // ? ? ? ? ? cancelButtonText: '取消', ? // ? ? ? ? ? type: 'warning' ? // ? ? ? ? }).then(() => { ? // ? ? ? ? ? store.dispatch('FedLogOut').then(() => { ? // ? ? ? ? ? ? location.reload();// 為了重新實(shí)例化vue-router對象 避免bug ? // ? ? ? ? ? }); ? // ? ? ? ? }) ? // ? ? ? } ? // ? ? ? return Promise.reject('error'); ? // ? ? } else { ? // ? ? ? return response.data; ? // ? ? } ? error => { ? ? console.log('err' + error)// for debug ? ? Message({ ? ? ? message: error.message, ? ? ? type: 'error', ? ? ? duration: 5 * 1000 ? ? }) ? ? return Promise.reject(error) ? }) export default service
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
spring-cloud-stream的手動消息確認(rèn)問題
這篇文章主要介紹了spring-cloud-stream的手動消息確認(rèn)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05Vue3 + MybatisPlus實(shí)現(xiàn)批量刪除功能(詳細(xì)代碼)
這篇文章主要介紹了Vue3 + MybatisPlus實(shí)現(xiàn)批量刪除功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-03-03Vue2.0使用嵌套路由實(shí)現(xiàn)頁面內(nèi)容切換/公用一級菜單控制頁面內(nèi)容切換(推薦)
這篇文章主要介紹了Vue2.0使用嵌套路由實(shí)現(xiàn)頁面內(nèi)容切換/公用一級菜單控制頁面內(nèi)容切換,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05Vue實(shí)現(xiàn)點(diǎn)擊箭頭上下移動效果
這篇文章主要介紹了Vue實(shí)現(xiàn)點(diǎn)擊箭頭上下移動效果,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06vue基于element-ui的三級CheckBox復(fù)選框功能的實(shí)現(xiàn)代碼
最近vue項(xiàng)目需要用到三級CheckBox復(fù)選框,需要實(shí)現(xiàn)全選反選不確定三種狀態(tài)。這篇文章主要介紹了vue基于element-ui的三級CheckBox復(fù)選框功能的實(shí)現(xiàn)方法,需要的朋友可以參考下2018-10-10vue中ref引用操作DOM元素的實(shí)現(xiàn)
本文主要介紹了vue中ref引用操作DOM元素的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01