vue中调接口的方式详解this.$api、直接调用、axios

 更新时间:2023年11月16日 09:25:08   作者:一枚小小菜鸟鸟  
这篇文章主要介绍了vue中调接口的方式:this.$api、直接调用、axios,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

1. this.$api

在api文件下层级关系如下图:

在index.js下

// 导入所有接口
import api from './api'
const install = Vue => {
  if (install.installed)
    return;
  install.installed = true;
  Object.defineProperties(Vue.prototype, {
    // 注意,此处挂载在 Vue 原型的 $api 对象上
    $api: {
      get() {
        return api
      }
    }
  })
}
export default install

在api.js

/*接口统一模块*/
import * as LeadershipScreen from './componet/LeadershipScreen'
export default {
    LeadershipScreen
}
/*使用模板
*  this.$api.auditApi.auditDataAll().then(response=>{
      }).catch(error=>{
      })
      */

在componet/LeadershipScreen.js

import { request } from "../../utils/request6";
export const getImportantRiskList = (data) => {
//allUrl2 可以写一个公共的地方将allUrl2 引进来
    return request({
        method: 'get',
        url: allUrl2 + '/important/getImportantRiskList',
        data
    });
};

在页面中使用

 this.$api.LeadershipScreen
        .getImportantRiskList(params)
        .then((res) => {
          console.log("res.data111111111111", res.data);
          this.getList = res.data;
        })
        .catch((error) => {});
//methodName:null;
let params={}
this.methodName = this.$api.LeadershipScreen.getImportantRiskList;
this.methodName(params)
        .then((res) => {
          console.log("res", res);
        })
        .catch((error) => {});

2.引用,然后直接调用

定义在api.js文件中

import request from '@/utils/request'
export const selectTaskInfo = (id, params) => request({ url: '/project-mgt/project/v1.0/selectTaskInfo?taskId=' + id, method: 'get', params })
export function setFormulaConfig(params) { return request({ url: '/project-mgt/project/v1.0/formulaConfig', method: 'get', params }) }//此处的params,会自动将参数拼在后面,data则不会
export const projectSelectionAdd = (data) => request({ url: '/project-mgt/project/v1.0/add', method: 'post', data })

使用

import {
  selectTaskInfo, 
  setFormulaConfig, 
  projectSelectionAdd ,
} from "@/code/projectSelection/api/projectSelectionApi";
//一种:直接传递id,
selectTaskInfo(id)
   .then((res) => {
       console.log("resaaaaaaaa", res.data);
   })
    .catch((err) => {
       console.log(err);
   });
 //一种:直接传递一个对象
let params = {
      id: this.Form.id,
};
setFormulaConfig(params)
    .then((res) => {
    if (res.code == "200") {
        console.log("resaaaaaaaa", res.data);
        this.$message.success("成功");
     }
  })
   .catch((err) => {
  });
 //一种:三元表达式根据不同的情况进行调用不同的接口
let interfaceName =
  this.$route.query.state == "add"
    ? projectSelectionAdd
    : projectUpdate;
interfaceName(params)
  .then((res) => {
    if (res.code == "200") {
      this.$message.success(
        this.$route.query.state == "add" ? "新增" : "修改"
      );
    } else {
      this.$message.error(res.msg);
    }
  })
  .catch((err) => {});

3.axios(需要先安装axios)

import axios from "axios";

get

// 为给定 ID 的 user 创建请求
const config = {
     headers:{"userId":1212}
};
axios.get('/user?ID=12345',config)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
// 可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

post

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

https://www.kancloud.cn/yunye/axios/234845
下面的比较好,推荐使用

getQuestionSurvey() {
      let testUrl = "";
      if (process.env.NODE_ENV === "development") {
        testUrl = "http://192.168.121.2:8080";//模拟,并非真实地址
      } else {
        testUrl = process.env.VUE_APP_BASE_API;
      }
      testUrl = testUrl + "/getFillReportById/" + this.id;
      axios({
        method: "get",
        url: testUrl,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          userId: this.userId,
        },
      })
        .then((res) => {
          //if (this.state != "editAjustMent") {
           // this.tableData1.forEach((item, index) => {
           //   for (const key in item.detailVoMap) {
           //     if (key.length > 17) {
            //      item.detailVoMap[key].fixedFlag = 0;
           //     }
              //}
            //});
          //}
        })
        .catch((err) => {
          console.log(
            "err.response.data",
            err.response,
            err.response.data,
            err.response.data.data,
            err.response.data.msg
          );
          this.$message.error(
            err.response.data.data
              ? err.response.data.data
              : err.response.data.msg
          );
        });
    },

4.配置request

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import qs from 'qs'
import cookieStore from '@/utils/common';
// Vue.prototype.$cookieStore = cookieStore;
// create an axios instance
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 500000000 // request timeout
})
// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        if (config.requestType === 'form') {
            config.headers = { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' }
            console.log('form')
            config.data = qs.stringify(config.data, { indices: false })
        } else if (config.requestType === 'json' || !config.requestType) {
            console.log('json')
            config.headers = { 'content-type': 'application/json;charset=UTF-8' }
        }
        if (store.getters.token) {
            config.headers['Authorization'] = getToken()
        }
        //加请求头
        config.headers['userId'] = "1036465471609819137"; //1
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)
// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code == 200) {
            return Promise.resolve(res)
        } else if (res.code == 0) {
            return Promise.resolve(res)
        } else if (res.code == 401) {
            Message.error(res.msg)
            store.dispatch('user/resetToken').then(() => {
                location.reload()
            })
        } else if (res.code == 20000) {
            return Promise.resolve(res)
        } else {
            Message({
                message: res.msg,
                type: 'error'
            })
            return Promise.reject(res)
        }
    },
    error => {
        console.log('err' + error) // for debug
        console.log(error.response)
        Message({
            message: error.response.data.data ? error.response.data.data : error.response.data.msg,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error.response)//此操作,可以直接拿到报错的信息error.response
    }
)
export default service

到此这篇关于vue中调接口的方式:this.$api、直接调用、axios的文章就介绍到这了,更多相关vue调接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • element上传组件循环引用及简单时间倒计时的实现

    element上传组件循环引用及简单时间倒计时的实现

    这篇文章主要介绍了element上传组件循环引用及简单时间倒计时的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-10-10
  • Nuxt使用Vuex解读

    Nuxt使用Vuex解读

    这篇文章主要介绍了Nuxt使用Vuex的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • vue基础入门之vuex安装与使用

    vue基础入门之vuex安装与使用

    vuex是一个专为vue.js应用程序开发的 状态管理模式,它采用集中式存储管理应用的所有的状态,并以相应的规则保证状态以一种可预测的方式发生变化,这篇文章主要给大家介绍了关于vue入门之vuex安装与使用的相关资料,需要的朋友可以参考下
    2021-08-08
  • Elementui el-input输入框校验及表单校验实例代码

    Elementui el-input输入框校验及表单校验实例代码

    输入框是使用非常多的元素,用来输入用户名、密码等等信息,Element提供了功能和样式丰富的输入框,下面这篇文章主要给大家介绍了关于Elementui el-input输入框校验及表单校验的相关资料,需要的朋友可以参考下
    2023-06-06
  • Vue之Axios异步通信详解

    Vue之Axios异步通信详解

    这篇文章主要为大家介绍了Vue之Axios异步通信,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-11-11
  • 记录一个Vue3简易微信右滑删除逻辑的思路实现

    记录一个Vue3简易微信右滑删除逻辑的思路实现

    本文主要介绍了记录一个Vue3简易微信右滑逻辑的思路实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-07-07
  • React和Vue实现路由懒加载的示例代码

    React和Vue实现路由懒加载的示例代码

    路由懒加载是一项关键技术,它可以帮助我们提高Web应用的加载速度,本文主要介绍了React和Vue实现路由懒加载的示例代码,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01
  • Vue3组件通信的具体用法实例

    Vue3组件通信的具体用法实例

    在Vue.js3中,组件通信主要包括父子组件通信、兄弟组件通信以及祖孙组件通信,这篇文章主要介绍了Vue3组件通信具体用法的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-09-09
  • vue项目中使用axios遇到的相对路径和绝对路径问题

    vue项目中使用axios遇到的相对路径和绝对路径问题

    这篇文章主要介绍了vue项目中使用axios遇到的相对路径和绝对路径问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • Vue.js 实现地址管理页面思路详解(地址添加、编辑、删除和设置默认地址)

    Vue.js 实现地址管理页面思路详解(地址添加、编辑、删除和设置默认地址)

    这篇文章主要介绍了Vue.js 实现地址管理页面的思路(地址添加、编辑、删除和设置默认地址),本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-12-12

最新评论