溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vue中axios的封裝問題(簡(jiǎn)易版攔截,get,post)

發(fā)布時(shí)間:2020-10-16 18:49:02 來源:腳本之家 閱讀:129 作者:陳88 欄目:web開發(fā)

第一步還是先下載axios

npm install axios --save

第二步/src/utils/目錄下建立一個(gè)htttp.js

import axios from 'axios';
axios.defaults.timeout = 5000;
axios.defaults.baseURL ='';
//http request 攔截器
axios.interceptors.request.use(
 config => {
  // const token = getCookie('名稱');
  config.data = JSON.stringify(config.data);
  config.headers = {
   'Content-Type':'application/x-www-form-urlencoded'
  }
  // if(token){
  //  config.params = {'token':token}
  // }
  return config;
 },
 error => {
  return Promise.reject(err);
 }
);
//http response 攔截器
axios.interceptors.response.use(
 response => {
  if(response.data.errCode ==2){
   router.push({
    path:"/login",
    querry:{redirect:router.currentRoute.fullPath}//從哪個(gè)頁(yè)面跳轉(zhuǎn)
   })
  }
  return response;
 },
 error => {
  return Promise.reject(error)
 }
)
/**
 * 封裝get方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function fetch(url,params={}){
 return new Promise((resolve,reject) => {
  axios.get(url,{
   params:params
  })
  .then(response => {
   resolve(response.data);
  })
  .catch(err => {
   reject(err)
  })
 })
}
/**
 * 封裝post請(qǐng)求
 * @param url
 * @param data
 * @returns {Promise}
 */
 export function post(url,data = {}){
  return new Promise((resolve,reject) => {
   axios.post(url,data)
     .then(response => {
      resolve(response.data);
     },err => {
      reject(err)
     })
  })
 }

第三步

在main.js中引入

import {post,get} from './utils/http'
//定義全局變量
Vue.prototype.$post=post;
Vue.prototype.$get=get;

最后在組件里直接使用

mounted(){
  this.$post('/api/v2/movie/top250')
   .then((response) => {
    console.log(response)
   })
 },

其余的方法一樣

總結(jié)

以上所述是小編給大家介紹的vue中axios的封裝問題(簡(jiǎn)易版攔截,get,post),希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI