我們在實(shí)際的Vue項(xiàng)目中經(jīng)常需要與后端進(jìn)行數(shù)據(jù)交互,但是在很大程度上我們需要用到這個插件绿贞,但是這里需要注意的一點(diǎn)是:在使用axios插件時因块,需要確認(rèn)你的Vue項(xiàng)目是不是vue-cli,這是前提條件籍铁。到這里我們需要安裝axios,這時候需要用npm進(jìn)行全局安裝涡上,如:
npm? install? --save? axios? vue-axios? qs
這里有一點(diǎn)需要注意:qs 是一個增加了一些安全性的查詢字符串解析和序列化字符串的庫。
等待安裝完成拒名,在安裝完成后吩愧,如何使用呢?
那么既然要使用就肯定要引用到Vue項(xiàng)目中增显,如何引用呢雁佳?
我們在Vue項(xiàng)目的目錄文件中找到main.js文件,在main.js文件中引用:
//引入axios同云,并加到原型鏈中
import axios from 'axios';
Vue.prototype.$axios =axios;import QS from 'qs'; //用來解決vue中post請求(詳情)
Vue.prototype.qs = QS;
這里為了方便大家糖权,我特地給大家準(zhǔn)備了一個封裝好的demo版axios,個人建議:最好是在與main.js的同級目錄下新建個http.js文件炸站,并復(fù)制粘貼下面這段代碼星澳,其中相關(guān)的接口數(shù)據(jù)根據(jù)個人情況來定,定義完成即可使用旱易。
import axios from 'axios'
import qs from 'qs'
axios.defaults.timeout = 5000;? ? ? ? ? ? ? ? ? ? ? ? //響應(yīng)時間
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';? ? ? ? //配置請求頭
axios.defaults.baseURL = '';? //配置接口地址
//POST傳參序列化(添加請求攔截器)
axios.interceptors.request.use((config) => {
? ? //在發(fā)送請求之前做某件事
? ? if(config.method? === 'post'){
? ? ? ? config.data = qs.stringify(config.data);
? ? }
? ? return config;
},(error) =>{
? ? console.log('錯誤的傳參')
? ? return Promise.reject(error);
});
//返回狀態(tài)判斷(添加響應(yīng)攔截器)
axios.interceptors.response.use((res) =>{
? ? //對響應(yīng)數(shù)據(jù)做些事
? ? if(!res.data.success){
? ? ? ? return Promise.resolve(res);
? ? }
? ? return res;
}, (error) => {
? ? console.log('網(wǎng)絡(luò)異常')
? ? return Promise.reject(error);
});
//返回一個Promise(發(fā)送post請求)
export function fetchPost(url, params) {
? ? return new Promise((resolve, reject) => {
? ? ? ? axios.post(url, params)
? ? ? ? ? ? .then(response => {
? ? ? ? ? ? ? ? resolve(response);
? ? ? ? ? ? }, err => {
? ? ? ? ? ? ? ? reject(err);
? ? ? ? ? ? })
? ? ? ? ? ? .catch((error) => {
? ? ? ? ? ? ? ? reject(error)
? ? ? ? ? ? })
? ? })
}
////返回一個Promise(發(fā)送get請求)
export function fetchGet(url, param) {
? ? return new Promise((resolve, reject) => {
? ? ? ? axios.get(url, {params: param})
? ? ? ? ? ? .then(response => {
? ? ? ? ? ? ? ? resolve(response)
? ? ? ? ? ? }, err => {
? ? ? ? ? ? ? ? reject(err)
? ? ? ? ? ? })
? ? ? ? ? ? .catch((error) => {
? ? ? ? ? ? ? ? reject(error)
? ? ? ? ? ? })
? ? })
}
export default {
? ? fetchPost,
? ? fetchGet,
}
以上的準(zhǔn)備工作已經(jīng)完成禁偎,但是要知道我們在實(shí)際的開發(fā)中很多時候會遇到跨域這樣的問題腿堤,那么如何利用axios來解決呢?下面我們先設(shè)置項(xiàng)目代理:Vue-cli3.0的在pack-8'; //配置請求頭
axios.defaults.baseURL = ''; //配置接口地址
//POST傳參序列化(添加請求攔截器)
axios.interceptors.request.use((config) => {
? ? //在發(fā)送請求之前做某件事
? ? if(config.method === 'post'){
? ? ? ? config.data = qs.stringify(config.data);
? ? }
? ? return config;
},(error) =>{
? ? console.log('錯誤的傳參')
? ? return Promise.reject(error);
});
//返回狀態(tài)判斷(添加響應(yīng)攔截器)
axios.interceptors.response.use((res) =>{
? ? //對響應(yīng)數(shù)據(jù)做些事
? ? if(!res.data.success){
? ? ? ? return Promise.resolve(res);
? ? }
? ? return res;
}, (error) => {
? ? console.log('網(wǎng)絡(luò)異常')
? ? return Promise.reject(error);
});
//返回一個Promise(發(fā)送post請求)
export function fetchPost(url, params) {
? ? return new Promise((resolve, reject) => {
? ? ? ? axios.post(url, params)
? ? ? ? ? ? .then(response => {
? ? ? ? ? ? ? ? resolve(response);
? ? ? ? ? ? }, err => {
? ? ? ? ? ? ? ? reject(err);
? ? ? ? ? ? })
? ? ? ? ? ? .catch((error) => {
? ? ? ? ? ? ? ? reject(error)
? ? ? ? ? ? })
? ? })
}
////返回一個Promise(發(fā)送get請求)
export function fetchGet(url, param) {
? ? return new Promise((resolve, reject) => {
? ? ? ? axios.get(url, {params: param})
? ? ? ? ? ? .then(response => {
? ? ? ? ? ? ? ? resolve(response)
? ? ? ? ? ? }, err => {
? ? ? ? ? ? ? ? reject(err)
? ? ? ? ? ? })
? ? ? ? ? ? .catch((error) => {
? ? ? ? ? ? ? ? reject(error)
? ? ? ? ? ? })
? ? })
}
export default {
? ? fetchPost,
? ? fetchGet,
}
以上的準(zhǔn)備工作已經(jīng)完成如暖,但是要知道我們在實(shí)際的開發(fā)中很多時候會遇到跨域這樣的問題笆檀,那么如何利用axios來解決呢?下面我們先設(shè)置項(xiàng)目代理:可以在Vue-cli3.0的packsge.json的同級目錄下創(chuàng)建一個vue.config.js文件盒至,復(fù)制粘貼下面這段代碼即可(當(dāng)然你的項(xiàng)目中已經(jīng)配置好了相關(guān)的代理信息误债,在你的配置文件中復(fù)制粘貼下面這段代碼即可)
module.exports = {
? ? //axios域代理,解決axios跨域問題
? ? baseUrl: '/',
? ? devServer: {
? ? ? ? proxy: {
? ? ? ? ? ? '': {
? ? ? ? ? ? ? ? target: 'http://192.168.0.108:8888',//注意這里的端口設(shè)置根據(jù)實(shí)際項(xiàng)目開發(fā)的情況而定妄迁,這是我現(xiàn)在未被占用的端口號;
? ? ? ? ? ? ? ? changeOrigin: true,
? ? ? ? ? ? ? ? ws: true,
? ? ? ? ? ? ? ? pathRewrite: {
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
此時保存好所有文件李命,重啟項(xiàng)目應(yīng)用配置即可登淘。
到這里的時候我們的安裝與配置均已準(zhǔn)備完成,那么在頁面中如何使用呢封字?
注意在你需要進(jìn)行交互的Vue頁面中導(dǎo)入并使用黔州,如:
import https from '../https.js' // 注意用自己的http.js文件路徑
// 請求后臺數(shù)據(jù)==================
? ? ? ? ? ? loginPost: function () {
? ? ? ? ? ? ? ? let params ={'username': 'admin', 'password': 'admin123', 'rememberMe': 'true','isMobile':'1'}
? ? ? ? ? ? ? ? https.fetchPost('/login',params ).then((data) => {
? ? ? ? ? ? ? ? ? ? this.base.token = data.data.token
? ? ? ? ? ? ? ? ? ? // console.log("this.base.tokenthis.base.token",this.base.token)
? ? ? ? ? ? ? ? ? ? this.indexPost2(this.rres)
? ? ? ? ? ? ? ? }).catch(err=>{
? ? ? ? ? ? ? ? ? ? ? ? console.log(err)
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? )
? ? ? ? ? ? },
? ? ? ? ? ? indexPost2:function (date) {
? ? ? ? ? ? ? ? var this_ = this
? ? ? ? ? ? ? ? this_.check = false
? ? ? ? ? ? ? ? var jobj ={data:{'menuDate': date,'token':this.base.token}}
? ? ? ? ? ? ? ? let string? = JSON.stringify(jobj)
? ? ? ? ? ? ? ? let params = {dailyInfo:string}
? ? ? ? ? ? ? ? https.fetchPost('/meals/mobile/getDailyMenuByDate', params)
? ? ? ? ? ? ? ? .then((data) => {
? ? ? ? ? ? ? ? ? ? this_.base.indexData = data
? ? ? ? ? ? ? ? ? ? this_.check = true
? ? ? ? ? ? ? ? ? ? // console.log('thenthenthenthen',data)
? ? ? ? ? ? ? ? })
? ? ? ? ? ? ? ? .catch((err)=>{
? ? ? ? ? ? ? ? ? ? console.log(err)
? ? ? ? ? ? ? ? })
? ? ? ? ? ? },
? ? ? ? ? ? // ================================================
? ? ? ? },
這樣就已經(jīng)完成了。
本文內(nèi)容主要轉(zhuǎn)載于:https://www.cnblogs.com/nogodie/p/9853660.html
分類:vue.js阔籽;