国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

vue中調(diào)接口的方式:this.$api、直接調(diào)用、axios

這篇具有很好參考價值的文章主要介紹了vue中調(diào)接口的方式:this.$api、直接調(diào)用、axios。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

1. this.$api

在api文件下層級關系如下圖:
this.$api,vue.js,vue.js,javascript,前端

在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

/*接口統(tǒng)一模塊*/
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.引用,然后直接調(diào)用

定義在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,會自動將參數(shù)拼在后面,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) => {
  });
  
 //一種:三元表達式根據(jù)不同的情況進行調(diào)用不同的接口
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 創(chuàng)建請求
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
下面的比較好,推薦使用文章來源地址http://www.zghlxwxcb.cn/news/detail-812875.html

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中調(diào)接口的方式:this.$api、直接調(diào)用、axios的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • spring boot java項目整合Scala&Spark,接口api調(diào)用方式調(diào)用scala代碼,配置分享

    spring boot java項目整合Scala&Spark,接口api調(diào)用方式調(diào)用scala代碼,配置分享

    版本說明: spring boot: 2.5.9 jdk:1.8 spark:2.4.5 sclala:2.11.12 首先你需要有一個完美的spring boot項目(java版本)能成功運行,這就不贅述了,按照網(wǎng)上的自己搭建吧,然后重要的來了,我搗鼓了兩天時間,各樣的報錯見過了,網(wǎng)上的處理方法要嘛是不全,要嘛是沒有用,各種辦

    2024年02月10日
    瀏覽(30)
  • 如何在vue項目中調(diào)用chatgpt的API接口

    在Vue項目中調(diào)用ChatGPT的API接口需要以下步驟: 在Vue項目中安裝axios,使用以下命令進行安裝: 在Vue項目中創(chuàng)建一個API模塊,用于封裝與ChatGPT的API交互邏輯??梢栽陧椖扛夸浵聞?chuàng)建一個api目錄,并在該目錄下創(chuàng)建一個chatgpt.js文件,代碼如下: 在Vue組件中引入API模塊,并調(diào)

    2023年04月25日
    瀏覽(22)
  • Vue調(diào)用后端api接口出現(xiàn)跨域問題,只要三步解決問題

    Vue調(diào)用后端api接口出現(xiàn)跨域問題,只要三步解決問題

    問題: 當我們在自己的個人電腦上去進行vue調(diào)用后端的操作時,經(jīng)常會遇到跨域問題 解決方式: 1.在Vue項目中調(diào)用api接口的地方加上 2.在后端代碼項目重寫Filter類 3. 在控制類方法上加上允許跨域的注解 搞定收工: ?

    2024年02月15日
    瀏覽(17)
  • restTemplate調(diào)用外部接口,調(diào)用返回307,用postman直接調(diào)用接口正常返回數(shù)據(jù)

    restTemplate調(diào)用外部接口,調(diào)用返回307,用postman直接調(diào)用接口正常返回數(shù)據(jù)

    restTemplate調(diào)用外部接口,調(diào)用返回307,用postman直接調(diào)用接口正常返回數(shù)據(jù) 結論:調(diào)用的接口路徑后加/ postman 關掉自動重定向(filesettins把Automatically follow redirects關掉),調(diào)用也同樣返回307了 在網(wǎng)上各種搜307,出來的結果都是什么重定向 getHeaders().getLocation().toString() 獲得返回

    2024年02月03日
    瀏覽(64)
  • 解決Django中調(diào)頁面時出現(xiàn)“Did you forget to register or load this tag”報錯

    解決Django中調(diào)頁面時出現(xiàn)“Did you forget to register or load this tag”報錯

    在HTML文件中,{{title}},{{lanyy}},django 默認規(guī)定的語法,用{{}}包起來的變量叫做模板變量。 django渲染模板時會將大括號中的變量替換為循環(huán)調(diào)用變量,最后顯示的是傳遞的值。 {% load static %} 正確的引入static文件下的CSS和JavaScript。 用{% %}包起來的叫做模板標簽。 {% empty %}的作

    2024年04月25日
    瀏覽(19)
  • 通過API接口調(diào)用數(shù)據(jù)的優(yōu)勢是什么?API接口調(diào)用展示示例

    通過API接口調(diào)用數(shù)據(jù)的優(yōu)勢主要有以下幾點: 1.規(guī)范化與一致性:API接口提供一種統(tǒng)一的方式來獲取數(shù)據(jù),保證了數(shù)據(jù)的規(guī)范化與一致性,消除了不同數(shù)據(jù)源可能帶來的格式和結構上的差異。 2.靈活性:使用API接口可以定制請求的參數(shù)和返回結果,讓請求方可以得到所需的數(shù)

    2024年02月06日
    瀏覽(22)
  • Vue父組件調(diào)用子組件方法this.$refs用法

    Vue父組件調(diào)用子組件方法this.$refs用法

    1. 介紹 2.父組件調(diào)用子組件的方法 2.1.父組件 代碼刪除了一部分,可能復制會報錯 2.2.子組件 3.效果 點擊彈窗修改框

    2024年02月07日
    瀏覽(20)
  • vue直接使用高德api

    vue直接使用高德api

    第一步:在index.html 引入 第二步:在你需要地圖的時候 放入 ?以上就是 如果需要其他的方法 請 訪問 官網(wǎng)?? 概述-地圖 JS API 2.0 | 高德地圖API

    2024年02月11日
    瀏覽(14)
  • 寶塔快速反代openai官方的API接口,實現(xiàn)國內(nèi)直接使用GPT

    寶塔快速反代openai官方的API接口,實現(xiàn)國內(nèi)直接使用GPT

    這是技術最簡單,最容易實現(xiàn)的,之前介紹過的一個《利用騰訊云函數(shù)免費部署國內(nèi)直接使用GPT代理,解決網(wǎng)絡不可用及1020等問題》,實現(xiàn)起來比較復雜,步驟太多,容易出錯漏掉的環(huán)節(jié),從而導致失敗,今天就再介紹一個最簡單,零代碼、零部署——反代法。 有一臺海外

    2023年04月10日
    瀏覽(29)
  • 怎么調(diào)用api接口

    1 .API接口是一種通信協(xié)議,用于不同的應用程序之間的數(shù)據(jù)交換。要編寫API接口,需要遵循以下步驟: 確定API的用途和功能。 設計API接口,并確定所有輸入和輸出參數(shù)。 編寫API代碼,包括數(shù)據(jù)驗證、邏輯處理和錯誤處理。 將API暴露給外部應用程序,通常是通過RESTful或SOAP協(xié)

    2024年02月07日
    瀏覽(35)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包