返回顶部
首页 > 资讯 > 前端开发 > JavaScript >Vue3引入axios封装接口的两种方法实例
  • 460
分享到

Vue3引入axios封装接口的两种方法实例

2024-04-02 19:04:59 460人浏览 泡泡鱼
摘要

目录第一种1.安装2.新建一个Http.js文件3.使用第二种1.安装2.新建3.http.js4.request.js总结 第一种 1.安装 npm install axiOS -

第一种

1.安装

npm install axiOS -S

2.新建一个http.js文件

import axios from "axios";
import qs from "qs";
import {
  Dialog,
  Toast
} from "vant";

// axios.defaults.baseURL = 'http://hplqy.suoluomei.cn/index.PHP?s=/hfs/api/'  //正式
axios.defaults.baseURL = 'http://activitytest.hpl001.cn/crm_api/app/sinceOrder/' //测试

//post请求头
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-fORM-urlencoded;charset=UTF-8";
//设置超时
axios.defaults.timeout = 10000;

axios.interceptors.request.use(
  config => {
    Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
    });
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    Toast.clear();
    return response;
  },
  error => {
    Toast.clear();
    Dialog.alert({
      title: "提示",
      message: "网络请求失败,反馈给客服"
    });
  }
);

export default function axiosApi(type, params, method) {
  let sign = process.env.Vue_APP_SIGN
  if (process.env.node_ENV === 'production') {
    sign = localStorage.getItem("wx_sign")
  } else {
    sign = 'crm:user:sign:f0c8cbe468f6a34463D198268290903f'
  }
  var value = {
    sign: sign
  }
  var data = method == "post" ? qs.stringify(Object.assign(value, params)) : Object.assign(value, params)
  return new Promise((resolve, reject) => {
    axios({
        method: method,
        url: type,
        data: data
      })
      .then(res => {
        if (res.data.errcode == 0) {
          resolve(res.data)
        } else {
          // 接口错误提示
          Toast.fail(res.data.msg);
        }
      })
      .catch(err => {
        reject(err)
      });
  })
};

3.使用

import axiosApi from "../utils/http";
tabsHttp() {
      axiosApi("getProductClassFromCrm", {}, "post").then((res) => {
        for (let i = 0; i < res.data.length; i++) {
          res.data[i].type = 0;
        }
        this.sebarList = res.data;
      });
    },

第二种

1.安装

npm install axios -S

2.新建

3.http.js

import axios from "axios";
import qs from "qs";
import {
  Dialog
} from "vant";

// axios.defaults.baseURL = 'http://hp.suoluomei.cn/index.php'  //正式
axios.defaults.baseURL = 'http://hp.suoluomei.cn/index.php' //测试

//post请求头
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";
//设置超时
axios.defaults.timeout = 10000;

axios.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    if (response.status == 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    Dialog.alert({
      title: "提示",
      message: "网络请求失败,请刷新重试"
    });
  }
);
export default {
  post(url, data) {
    return new Promise((resolve, reject) => {
      axios({
          method: 'post',
          url,
          data: qs.stringify(data),
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        });
    })
  },

  get(url, data) {
    return new Promise((resolve, reject) => {
      axios({
          method: 'get',
          url,
          params: data,
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
};

4.request.js

import http from './http'
const api_key = '233d4cad34c34d343785s34dw3er3ds3234esd4'
let sign = process.env.VUE_APP_SIGN
if (process.env.NODE_ENV === 'production') {
  sign = localStorage.getItem("sign")
} else {
  sign = '17a1920fdc3c3c25d1bf7c6dd724f5cf'
}

const post = (url, data = {}) =>
  http.post(
    url,
    Object.assign({
        api_key: api_key,
        sign,
      },
      // {
      //   data: Object.assign({
      //       role_id: role_id //如果需要再包层data就这样写
      //     },
      //     data
      //   )
      // }
      data
    )
  )
const get = (url, params = {}) =>
  http.get(
    url,
    Object.assign({
        api_key: api_key,
        sign
      },
      params
    )
  )

// 接口说明
const getFissionCourseList = data => post('getFissionCourseList', data)

const getGetrequs = params => get('getFissionCourseList', params)
//接口导出
export {
  getFissionCourseList,
  getGetrequs
}

5.页面引入使用

<template>
  <div class="box">
    <div class="yanjin">
      <div
        class="demo"
        ref='seder'
      >欢迎来到vue3</div>
      <div
        class="demo"
        @click="testClick"
      >欢迎来到VUE3</div>
    </div>
    <div @click="Go">跳转页面</div>
    <div @click="getRquset">
      点我调接口
    </div>
    <meHome :text='132'></meHome>
  </div>
</template>

<script>
import { getFissionCourseList, getGetrequs } from "../../utils/request";
import { Reactive, toRefs, onMounted, onActivated } from "vue";
import meHome from "../me/me.vue";
import { async } from "q";
export default {
  components: {
    meHome,
  },
  setup() {
    // data
    const state = reactive({
      testMsg: "原始值",
    });
    //onLand生命周期
    onMounted(async () => {
      // 进入页面调用接口
      init();
      console.log(state.testMsg);
    });

    // onshow生命周期
    onActivated(async () => {});
    // methods事件
    const methods = {
      go() {
        this.$router.push({
          path: "/main",
          query: {
            course_id: 123,
          },
        });
      },
      testClick() {
        this.$nextTick(() => {
          this.$refs.seder.innerhtml = "更改了内容";
        });
      },
      async getRquset() {
        await getGetrequs({ t35: "get" }).then((res) => {
          console.log(res);
        });
      },
    };
    const init = async () => {
      await getFissionCourseList({ t35: "post" }).then((res) => {
        // console.log(res);
      });
      await getGetrequs({ t35: "get" }).then((res) => {
        // console.log(res);
      });
    };
    return {
      ...toRefs(state),
      ...methods,
    };
  },
};
</script>

<style src='./index.less' lang='less' scoped>
</style>

总结

到此这篇关于Vue3引入axios封装接口的两种方法的文章就介绍到这了,更多相关Vue3引入axios封装接口内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Vue3引入axios封装接口的两种方法实例

本文链接: https://lsjlt.com/news/149548.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作