// 安裝axios(建立的vue項目的根目錄)
npm install axios;
❝「快捷方式(win+r)」 --> 「cmd」 --> 「輸入vue ui」 --> 「自動會跳轉8000端口(默認)」前端
❞
❝能夠配合全局攔截(請求攔截+響應攔截) 自行搜索vue
❞
import axios from "axios";
import qs from "qs";
let baseURL = "http://127.0.0.1:8080/";
// let baseURL = "";
// const test = {} 替換 export default
export default {
post(url, data) {
return axios({
method: "post",
url: `${baseURL}${url}`,
data: qs.stringify(data),
timeout: 10000
});
},
put(url, data) {
return axios({
method: "put",
url: `${baseURL}${url}`,
data: qs.stringify(data),
timeout: 10000
});
},
delete(url, data) {
return axios({
method: "delete",
url: `${baseURL}${url}`,
// url,
data: qs.stringify(data),
timeout: 10000,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
},
get(url, params) {
return axios({
method: "get",
url: `${baseURL}${url}`,
params: params, // get 請求時帶的參數
timeout: 10000
});
}
}
// 引入http.js
import http from '../utils/http'
abc(){
// 例如 md?articleId=1
var url = "後端路徑";
// 參數
var params = {
id: id,
key: value
}
// 好比在方法中調用get
http.get(url, params).then(resp => {
內容
})
}
❝參考文章裏最下面有ios
❞
import api from '../utils/http' // 導入api接口
Vue.prototype.$api = api; // 將api掛載到vue的原型上
this.$api.get()
// 如果不行 在http.js 將export default 替換爲 const test = {}
this.$api.test.get()
❝只是爲了學習一下store actionsgit
❞
actions: {
get(_, params){
// var url = reqParams.url;
// var params = reqParams.params;
// console.log("url ==>",url);
console.log("params ==>",params);
return http.get(params.url, params.params);
},
async post(_, reqParams){
var url = reqParams.url;
var params = reqParams.params;
return await http.post(url, params);
},
put(_, reqParams){
var url = reqParams.url;
var params = reqParams.params;
return http.put(url, params);
},
delete(_, reqParams){
var url = reqParams.url;
var params = reqParams.params;
return http.delete(url, params);
}
}
demo(id){
var url = "test/adc/";
var params = {
id: id
}
var data = {
url: url,
params: params
}
this.$store.dispatch("get", data).then(resp => {
console.log("resp -->", resp);
})
}
參考文章github
參考代碼web