vue-------------axios 封装全局js

之前项目新建 utils.js 后面的demo可以直接使用 、

新建utils.js目录



####  get 

//第一种  参数必须以  params
import Vue from 'vue'
下面写法方便 修改服务器地址
export async function clusterDetail(id) {
    return await Vue.axios.get(sessionStorage.getItem("mock") === 'true' ? '/mock/clusterDetail.json' : '/userCluster/query/detail', {
        params: {
            userClusterId: id
        }
    }).then((res) => {
        return res.data.data
    })
}

//第二种   
export async function loading() {
    return await Vue.axios({
        method:"GET",
        url:'/loading',
        params:{
           token :'afdb0bb8311a461d9a5026142cb50b4c',
           randomStr :'730bc5ae517b7bd088308d0ffd702a88',
           mchntOrderId :'80187107',
           sign :'LYEsaji8bQCV4e5Y8Rei0TqqyioTQa2nZxU91JB8zI2oxtJ0AwHq1VBusjcO0OWuBL1p1RCrJLp8HmtUEf8HqZmvjLChlwiwK4Vw0Jq58Hs=',
           transAt :'1',
         }
    }).then((res) => {
        return res
    }).catch(err=>{
        console.log(err);
    })
}


###post  接口  参数 data 
// 订单详情  utpCst/orderPayDetail
export async function orderPayDetail(data) {
    return await Vue.axios({
        method:"POST",
        url:'/orderPayDetail',
        data:{
            mchntOrderId:data.mchntOrderId,
            token : data.token
         }
    }).then((res) => {
        return res
    }).catch(err=>{console.log(err);
    })
}

在vue页面使用

<template>
<div class="box">
  <button @click="testQuestion">点击发送请求</button>
</div>
</template>

<script>
import * as Untils from "./utils.js";
export default {
  name: "HelloWorld",
   data() {
      return {
      };
   },
   created() {},
   methods: {
   
       testQuestion(){
         utils.test_quest().then(res=>{  //直接service
           console.log(res);
         })
       }
  }
};
</script>

demo------- 复制可使用-------

main.js页面

import axios from 'axios'  //npm i axios
import VueAxios from 'vue-axios'   //npm i vue-axios 如果请求报错 get  post  is undefind  去下载 npm i cue-axios
Vue.prototype.axios=axios
Vue.use(VueAxios, axios)  //如果单独引入axios   不引入vueaxios  或报错
 //配置基础路径


//如果单独引入axios 不引入vueaxios 或报错
在这里插入图片描述

新建utils/tagserve.js

import Vue from 'vue'
import axios from 'axios'

import { Toast ,Indicator} from "mint-ui";  //下载minu-ui  按需导入

let dev =false // 小程序base授权接口  true为生产  fase 开发
//axios基础配置  ---start
axios.defaults.baseURL= dev ?'http:':'http:/kfpifa/api'
axios.defaults.headers.common['Authorization'] = ''; 
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
// axios.defaults.timeout = 10000;
// axios.interceptors.response.use(undefined, function axiosRetryInterceptor(res,err) {
//     // Indicator.close()
//     alert(' 请求超时 ')
// })

//-------接口统一配置---start
// 小程序base授权接口
export const url = {
    base_auth  : dev ?  'https://': 'http:', 
    base_code  : dev ?  'https://': '', 
};


// 订单详情  utpCst/loading
export async function loading() {
    return await Vue.axios({
        method:"POST",
        url:'/loading',
        data:{
           token :'afdb0bb8311a461d9a5026142cb50b4c',
           randomStr :'730bc5ae517b7bd088308d0ffd702a88',
           mchntOrderId :'80187107',
           sign :'LYEsaji8bQCV4e5Y8Rei0TqqyioTQa2nZxU91JB8zI2oxtJ0AwHq1VBusjcO0OWuBL1p1RCrJLp8HmtUEf8HqZmvjLChlwiwK4Vw0Jq58Hs=',
           transAt :'1',
         }
    }).then((res) => {
        return res
    }).catch(err=>{
        console.log(err);
    })
}


// 订单详情  utpCst/orderPayDetail
export async function orderPayDetail(data) {
    return await Vue.axios({
        method:"POST",
        url:'/orderPayDetail',
        data:{
            mchntOrderId:data.mchntOrderId,
            token : data.token
         }
    }).then((res) => {
        return res
    }).catch(err=>{console.log(err);
    })
}

### ---------请求拦截 响应拦截-----------------------------

axios.interceptors.request.use(function (config) {
    // Do something before request is sent
      Indicator.open()
    return config;
  }, function (error) {
      Indicator.close()
   
    // Do something with request error
    return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Do something with response data
    Indicator.close()
    
    return response;
  }, function (error) {
    Indicator.close()
    Toast(' 请求超时 ')

    
    // Do something with response error
    return Promise.reject(error);
});


在组件中使用 import * as Untils from ‘…/utils/TagServer’;

  created(){
    Untils.Loading().then((res)=>{
      console.log(res);
      

    })
  },```

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端成长营

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值