1、安裝axiosvue
axios安裝命令:cnpm install axiosios
2、在文件中引用axiosnpm
一開始我是放在src下的main.js這個文件裏面,後來發現mounted鉤子讀取接口方法爲undefined,百度了才發現是vue生命週期的緣由,最好的解決辦法是把axios單獨抽取出來放在另一個文件中,爲此我在src下新建了一個api文件夾,文件名爲main.js(名字任意取)json
引用axiosaxios
import axios from 'axios'
import qs from 'qs' //qs庫-->做用是格式化數據
var TIME_OUT = 50000; //若是請求的時間超過'timeout',請求將被停止
var st_base_prefix = 'http://shira1.midea.com:1002';
const base_axios_options = {
headers:{ 'content-type': 'application/json' },
timeout:5000,
withCredentials:true, //是否跨站點訪問控制請求
};
const org_base = `${st_base_prefix}/st-sys/authority`;
const orgAxios = axios.create(Object.assign({},{ baseURL:org_base },base_axios_options));
export const orgModuleApi={
save:(params)=>{
return orgAxios.post('/sysOrg/save',params).then(res=>res.data);
},
getByPage:(params)=>{
return orgAxios.post('/sysOrg/getByPage?'+qs.stringify(params)).then(res=>res.data);
},
test:(params)=>{
//return "test";
return orgAxios.get('/sysOrg/test',params).then(res=>res.data);
}
}
<script> import {orgModuleApi} from '../../../api/main.js'; export default(){ data(){ return{ } }, methods:{ getByPage(){ orgModuleApi.getByPage({pageNo:this.pageNo,pageSize:this.pageSize}).then(res=>{ if(res.code){ console.log("123"); } }) }, getTest(){ orgModuleApi.test().then(res=>{ if(res.code){ console.log('success'); } }) } }, mounted(){ this.getByPage(); this.getTest(); } } </script>