vue封装axios接口
生活随笔
收集整理的這篇文章主要介紹了
vue封装axios接口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、安裝axios
axios安裝命令:cnpm install axios
二、在文件中引用axios
一開始我是放在src下的main.js這個文件里面,后來發現mounted鉤子讀取接口方法為undefined,百度了才發現是vue生命周期的原因,最好的解決辦法是把axios單獨抽取出來放在另外一個文件中,為此我在src下新建了一個api文件夾,文件名為main.js(名字任意取)
引用axios
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); } }?
以上的代碼全都是寫在api-->main.js中 五、頁面中調用接口 <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>?
轉載于:https://www.cnblogs.com/shira-t/p/8520736.html
總結
以上是生活随笔為你收集整理的vue封装axios接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python关机linux_Python
- 下一篇: html5倒计时秒杀怎么做,vue 设