在vue中封装Axios

vue封装axios和组件复用
在src目录下新建store文件夹
新建fetch.js文件
引入axios

import axios from ‘axios’ //引入依赖
export function fetch(options){ //定义fetch函数
return new Promise((resolve,reject)=>{ // 返回值
const instance =axios,create({ // 创建axios实例
headers:{ //此处是请求头中字段
‘Content-Type’ : ‘application/json’, // 解析格式
‘token’ : localStorage.getItem(‘obj’) // token从浏览器缓存中拿取,可以使用其他传参方式传递 如vuex
},
timeout: 5*1000 //超时时间
})
instance(options).then(response=>{ //请求成功之后得到response执行的操作
resolve(response)
})
.catch(error=>{ // 请求失败之后输出异常信息
console.log(‘请求异常信息’+error)
reject(error)
})
})
}

在store文件夹下新建js文件引入fetch文件实例化请求
如api.js中

import {fetch} form ‘./fetch’ // 引入fetch.js里面的fetch函数
import global_ from ‘…/Global’ // Global.vue中存储全局变量 主要是const了BASE_URL即是请求网址中重复的那部分
export function GetAllUser (page,name,email,roleName){ // 获取用户的接口函数,接收四个参数,页码,姓名,邮箱,和角色
return fetch ({ //这里使用fetch模块,请求中会自动带上请求头中的headers
url: global_.BASE_URL+’/user/getAlluser’, // url即是请求地址,拼接而成
method:‘post’, // 请求方法为post,参数为data,如果是get即用prams
data: JSON.stringify({ // 这里将需要传递给后台的参数转换类型为JSON字符串
page: page,
name:name,
email:email,
roleName:roleName
})
})
}

如果需要多个请求就像上面一样再写一个就好了,可以新建多个js文件将不同的接口类型分开
下面在vue组件中传递参数并执行成功之后的渲染

// html片段

// 在js 中调用上面的click方法来获取所有用户
import {GetAllUser} from '../../store/api'            // 此处将写好的请求引入组件中 form 路径要写对

// 在methods中执行

search(){    // 执行查询操作
GetAllUser(this.currentPage,this.name,this.email,this.region)   // 传递参数
.then((res)=>{  
this.total=res.data.num           // 请求成功之后将得到的总和值传递给total,显示在分页组件中
this.tabledata=res.data.data      //  请求到的data数据 一一对应表格中的参数,渲染在表格中
})
.catch((error)=>{                // 请求失败
console.log('请求异常:'error)          // 输出异常信息
})
}

一般项目中会写很多个请求,可以将同页面不同的请求封装起来,放在一个js文件中。

你可能感兴趣的:(vue学习)