1.開發環境 vue
2.電腦系統 windows 10 專業版
3.再開發的過程當中,咱們會使用到axios進行數據的交互,下面是我對axios的封裝,代碼以下:
3-1:總體目錄結構以下:
//只是初期的封裝,後面還會進行完善!
3-2:總體思路:爲何要進行封裝?封裝是爲了更加的方便,統一管理,更加的高效!
3-3:在src目錄下面新建一個文件,名字爲:utils!在 utils下面新建一個js文件,request。這個request 是把axios進行封裝!
3-3-1:request.js代碼以下:vue
import axios from 'axios' import qs from 'qs' axios.defaults.timeout = 5000; //響應時間 axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; //配置請求頭 axios.defaults.baseURL = 'http://192.168.0.106:3000/'; //配置接口地址 //POST傳參序列化(添加請求攔截器) axios.interceptors.request.use((config) => { //在發送請求以前作某件事 if(config.method === 'post'){ config.data = qs.stringify(config.data); } return config; },(error) =>{ console.log('錯誤的傳參') return Promise.reject(error); }); //返回狀態判斷(添加響應攔截器) axios.interceptors.response.use((res) =>{ //對響應數據作些事 if(!res.data.success){ return Promise.resolve(res); } return res; }, (error) => { console.log('網絡異常') return Promise.reject(error); }); //返回一個Promise(發送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(發送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, }
3-4:在src目錄下新建一個文件,api,api下面新建Login,Login文件下面新建 Login.js。目的,統一管理Login接口。
3-4-1:Login.js代碼以下:ios
import {fetchPost,fetchGet} from '../../utils/request' export function chen(chen) { return fetchPost('/feng',chen) } //備註:導入請求,fetchPost表示post請求,fetchGet表示get請求。在項目中,根據需求選擇。 fetchPost('/feng',chen) // '/feng' :表示請求地址 ; chen:表示請求須要傳的參數。
3-5:在vue組件中使用,在vue組件中添加以下代碼:axios
import {chen} from '../api/Login/Login'
3-5-1:在methods中添加以下代碼:windows
methods: { //頁面已加載就向後臺發送請求 chenget() { var kk = { name: '陳鵬' } chen(kk).then(res => { console.log(res); }) } }
3-5-2:在mounted中添加以下代碼:api
mounted() { this.chenget(); },
3-6:在vue.config.js中添加以下代碼:瀏覽器
module.exports = { devServer: { proxy: { '/api': { target: 'http://192.168.0.109:3000', ws: true, changeOrigin: true, pathRewrite: { '^/api': '' //經過pathRewrite重寫地址,將前綴/api轉爲/ } } } } }
3-7:在main.js中添加以下代碼:網絡
import axios from 'axios' axios.defaults.baseURL = "/api";
3-8:運行項目,打開瀏覽器,你就會看到對應的後臺請求的數據,效果以下:
app
3-9:本期的教程到了這裏就結束啦,是否是很nice,是否是感受本身又進步了不少,讓咱們一塊兒努力,走向巔峯。post