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>