当前位置:   article > 正文

vue封装axios

vue封装axios

(4条消息) Vue——axios的二次封装_前端杂货铺的博客-CSDN博客

1.下载axios依赖包

npm install axios

2.在src目录下新建utils文件夹,在utils文件夹下新建request.js文件

 3.request.js

  1. import axios from 'axios'
  2. import { Message, MessageBox } from 'element-ui' //导入element-ui组件库
  3. // 创建axios的对象
  4. const instance = axios.create({
  5. baseURL: "https://api.cat-shop.penkuoer.com", //配置固定域名
  6. timeout: 5000
  7. })
  8. // 请求拦截
  9. // 所有的网络请求都会走这个方法,可以在请求添加自定义内容
  10. instance.interceptors.request.use(
  11. function (config) {
  12. config.headers.token = '123456' // 请求头添加token值
  13. config.headers.info = 'lxy' //请求头添加info值
  14. return config
  15. },
  16. function (err) {
  17. return Promise.request(err)
  18. }
  19. )
  20. // 响应拦截
  21. // 此处可以根据服务器返回的状态码做相应的数据
  22. instance.interceptors.response.use(
  23. function (response) {
  24. const res = response
  25. if (res.status === 500) {
  26. MessageBox.alert('系统未登录,请重新登录', '错误', {
  27. confirmButtonText: '确定',
  28. type: 'error'
  29. }).then(() => {
  30. store.dispatch('FedLogOut').then(() => {
  31. location.reload()
  32. })
  33. })
  34. return Promise.reject('error')
  35. } else if (res.errno === 502) {
  36. MessageBox.alert('系统内部错误,请联系管理员维护', '错误', {
  37. confirmButtonText: '确定',
  38. type: 'error'
  39. })
  40. return Promise.reject('error')
  41. }
  42. },
  43. function (err) {
  44. return Promise.request(err)
  45. }
  46. )
  47. // 封装get和post请求
  48. export function get(url, params) {
  49. return instance.get(url, {params})
  50. }
  51. export function post(url, data) {
  52. return instance.post(url, data)
  53. }
  54. export default instance;

方式1:(最常用使用)

在src目录下新建api文件夹,在api文件夹中新建index.js用于存放请求接口

api目录下的index.js

  1. import request from "@/utils/request"; //导入封装请求的js文件
  2. export function products(params) {
  3. return request({
  4. url: "/api/v1/products", //接口路径
  5. method: "get", //接口方法
  6. headers: { 'Content-Type': 'multipart/form-data' }, //给接口添加请求头
  7. params //接口参数
  8. });
  9. }
  10. export function login(data) {
  11. return request({
  12. url: "/api/v1/auth/login",
  13. method: "post",
  14. data,
  15. // post请求接口后面拼接参数
  16. params: {
  17. currentOpenId: 'currentOpenId',
  18. currentCompanyOpenId: 'currentCompanyOpenId'
  19. }
  20. });
  21. }

页面使用:

  1. <template>
  2. <div>
  3. <button @click="get()">封装的get</button>
  4. <button @click="post()">post</button>
  5. </div>
  6. </template>
  7. <script>
  8. import {products,login} from "@/api/index" //导入api目录下的接口文件,并在{}中写使用的接口
  9. export default {
  10. methods: {
  11. get(){
  12. products({name:"lxy",age:18,date: new Date().getTime()}).then(res => {
  13. console.log('res',res.data);
  14. })
  15. },
  16. post(){
  17. let obj = {
  18. name:'lxy',
  19. age:18
  20. }
  21. login(obj).then(res => {
  22. console.log('res',res.data);
  23. })
  24. }
  25. },
  26. };
  27. </script>

方式2:(不常用)

request.js

  1. export function get(url, params) {
  2. return instance.get(url, {params})
  3. }
  4. export function post(url, data) {
  5. return instance.post(url, data)
  6. }

页面使用:

  1. <template>
  2. <div>
  3. <button @click="meGet()">封装的get</button>
  4. <button @click="mePost()">post</button>
  5. </div>
  6. </template>
  7. <script>
  8. import { get, post } from "@/utils/request";
  9. export default {
  10. methods: {
  11. // 方式1 在方法里直接写api路径
  12. meGet() {
  13. get("/api/v1/products",{name:'aaa',age:18}).then((res) => {
  14. console.log("res", res);
  15. });
  16. },
  17. mePost() {
  18. let obj = {
  19. name:108
  20. }
  21. post("/api/v1/auth/login", obj).then((res) => {
  22. console.log("res", res);
  23. });
  24. },
  25. },
  26. };
  27. </script>

方式3:原生方法

  1. methods:{
  2. getMthods(){
  3. axios.get("https://api.cat-shop.penkuoer.com/api/v1/products",{
  4. params:{
  5. page:3,
  6. per:2
  7. },
  8. headers:{
  9. }
  10. })
  11. .then(res => {
  12. console.log('res',res);
  13. })
  14. },
  15. postMthods(){
  16. axios.post("https://api.cat-shop.penkuoer.com/api/v1/auth/login",{
  17. name:"lxy",
  18. age:18
  19. },{
  20. params:{
  21. a:123,
  22. b:123
  23. }
  24. })
  25. .then(res => {
  26. console.log('res',res);
  27. })
  28. },
  29. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/257087
推荐阅读
  

闽ICP备14008679号