当前位置 : 主页 > 网络编程 > JavaScript >

vue中三种调用接口的方法

来源:互联网 收集:自由互联 发布时间:2023-02-08
目录 1. this.$api.LeadershipScreen.getImportantRiskList(params) 2.需要引用 3.axios(需要先安装axios) 4.配置request 1. this.$api.LeadershipScreen.getImportantRiskList(params) 在api文件下层级关系如下图: 在index.j
目录
  • 1. this.$api.LeadershipScreen.getImportantRiskList(params)
  • 2.需要引用
  • 3.axios(需要先安装axios)
  • 4.配置request

1. this.$api.LeadershipScreen.getImportantRiskList(params)

在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.需要引用

定义

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";
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)

get

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .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 el-table实现递归嵌套的示例代码
下一篇:没有了
网友评论