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

news/2024/7/10 1:05:38 标签: vue, vue 请求封装, axios, 前端

文章目录

    • 之前项目新建 utils.js 后面的demo可以直接使用 、
    • 新建utils.js目录
    • demo------- 复制可使用-------
    • main.js页面
    • 新建utils/tagserve.js
    • 在组件中使用 import * as Untils from '../utils/TagServer';

之前项目新建 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);
      

    })
  },```


http://www.niftyadmin.cn/n/1836479.html

相关文章

vue -------------- el-dialog 对话框 封装

el-dealog 对话框 封装 代码如下 复制粘贴可用 <template> <div class"box"> <el-button class"oprattion" click"showhowDetailDialog(111, submmitSearch)">提交查询</el-button> <el-button class"oprattio…

ComboBox和SelectedIndexChanged(转)

ComboBox双击,自动生成的SelectedIndexChanged事件,如果说ComboBox不做数据绑定,通常我们则只需要得到一个Selectindex值也就可以了,但如果做数据绑定,那么我们想获得的操作值的要强也就提高了,比如我们做这么一个绑定: combobox1.datasourcedt; ///dt是一个TataTablecombobox1…

vue vuex的数据状态管理使用-----------------------------------------

VUEX 的数据状态管理 简单的使用 npm install vuex --save //安装vuex在src 目录新建 store 文件夹 建立index.js 文件 main.js中 ruby import store from ./store new Vue({el: #app,router,store,components: { App },template: <App/> })import Vue from vue impor…

【转】Js 调用 WebService心得总结

页面&#xff1a; <INPUT type"button" value"Button" οnclick"getdata()"><br> <span id"div1" class"list"></span> <script languagejavascript> setInterval(getdata,1000); /…

缺陷管理之 BugFree安装问题

安装过程中遇到的问题&#xff1a; 1.解压 GreenAMP Standard Build 050123 后&#xff0c;双击“启动GreenAMP.bat”&#xff0c;结果提示“80端口被占用”&#xff0c;导致“Apache”和“MySQL”服务启动不了 解决方法&#xff1a; 1.找到占用80端口的进程或服务&#xff1b;…

H5页面 ios 兼容问题总汇

文章目录css 问题 display&#xff1a;flex 布局 中文会自动换行 英文不能自动换行 溢出问题input 输入框 键盘中文全键模式 获取不到拼音input 输入框在ios系统中 当disabledtrue 时 手机上的颜色很浅a 标签 htef “#” ios 会闪屏css 问题 display&#xff1a;flex 布局 中文…

回家感悟

回家休了一周归来&#xff0c;记点东西。 房子 坚持了好几年&#xff0c;爸妈终于搬进了新房&#xff0c;房子是在亲戚朋友的帮助下装修的…简单漂亮…我一点都没操心。 早就承诺等爸妈搬新房的时候&#xff0c;给他们买个大电视&#xff0c;这次回家兑现了我的承诺。 对于…

usm 魔术师安装系统纯净版

1、USM支持多元化安装模式。 2、USM含有两套稳定而全面的SRS驱动&#xff0c;让你兼容更多机器的运行。 3、USM支持UEFI环境的安装。 4、USM无绑定任何推广插件及主页&#xff0c;没有任何“流氓”行为 。 5、USM接受定制版本&#xff0c;为您量身打造属于你自己的PE。 关于版…