最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2023年11月16日 09:25:08   作者:一枚小小菜鳥鳥  
這篇文章主要介紹了vue中調(diào)接口的方式:this.$api、直接調(diào)用、axios,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

1. this.$api

在api文件下層級關(guān)系如下圖:

在index.js下

// 導(dǎo)入所有接口
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 引進(jìn)來
    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) => {
  });
 //一種:三元表達(dá)式根據(jù)不同的情況進(jìn)行調(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
下面的比較好,推薦使用

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

到此這篇關(guān)于vue中調(diào)接口的方式:this.$api、直接調(diào)用、axios的文章就介紹到這了,更多相關(guān)vue調(diào)接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • element上傳組件循環(huán)引用及簡單時間倒計時的實現(xiàn)

    element上傳組件循環(huán)引用及簡單時間倒計時的實現(xiàn)

    這篇文章主要介紹了element上傳組件循環(huán)引用及簡單時間倒計時的實現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-10-10
  • Nuxt使用Vuex解讀

    Nuxt使用Vuex解讀

    這篇文章主要介紹了Nuxt使用Vuex的方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • vue基礎(chǔ)入門之vuex安裝與使用

    vue基礎(chǔ)入門之vuex安裝與使用

    vuex是一個專為vue.js應(yīng)用程序開發(fā)的 狀態(tài)管理模式,它采用集中式存儲管理應(yīng)用的所有的狀態(tài),并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測的方式發(fā)生變化,這篇文章主要給大家介紹了關(guān)于vue入門之vuex安裝與使用的相關(guān)資料,需要的朋友可以參考下
    2021-08-08
  • Elementui?el-input輸入框校驗及表單校驗實例代碼

    Elementui?el-input輸入框校驗及表單校驗實例代碼

    輸入框是使用非常多的元素,用來輸入用戶名、密碼等等信息,Element提供了功能和樣式豐富的輸入框,下面這篇文章主要給大家介紹了關(guān)于Elementui?el-input輸入框校驗及表單校驗的相關(guān)資料,需要的朋友可以參考下
    2023-06-06
  • Vue之Axios異步通信詳解

    Vue之Axios異步通信詳解

    這篇文章主要為大家介紹了Vue之Axios異步通信,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-11-11
  • 記錄一個Vue3簡易微信右滑刪除邏輯的思路實現(xiàn)

    記錄一個Vue3簡易微信右滑刪除邏輯的思路實現(xiàn)

    本文主要介紹了記錄一個Vue3簡易微信右滑邏輯的思路實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • React和Vue實現(xiàn)路由懶加載的示例代碼

    React和Vue實現(xiàn)路由懶加載的示例代碼

    路由懶加載是一項關(guān)鍵技術(shù),它可以幫助我們提高Web應(yīng)用的加載速度,本文主要介紹了React和Vue實現(xiàn)路由懶加載的示例代碼,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • Vue3組件通信的具體用法實例

    Vue3組件通信的具體用法實例

    在Vue.js3中,組件通信主要包括父子組件通信、兄弟組件通信以及祖孫組件通信,這篇文章主要介紹了Vue3組件通信具體用法的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-09-09
  • vue項目中使用axios遇到的相對路徑和絕對路徑問題

    vue項目中使用axios遇到的相對路徑和絕對路徑問題

    這篇文章主要介紹了vue項目中使用axios遇到的相對路徑和絕對路徑問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • Vue.js 實現(xiàn)地址管理頁面思路詳解(地址添加、編輯、刪除和設(shè)置默認(rèn)地址)

    Vue.js 實現(xiàn)地址管理頁面思路詳解(地址添加、編輯、刪除和設(shè)置默認(rèn)地址)

    這篇文章主要介紹了Vue.js 實現(xiàn)地址管理頁面的思路(地址添加、編輯、刪除和設(shè)置默認(rèn)地址),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-12-12

最新評論

宣城市| 涿州市| 东兴市| 喀什市| 扶风县| 和平区| 保靖县| 大城县| 叙永县| 和硕县| 自贡市| 车致| 郴州市| 绍兴县| 新源县| 聂荣县| 吴桥县| 孝昌县| 黄龙县| 阿鲁科尔沁旗| 竹北市| 烟台市| 湘西| 莲花县| 甘孜县| 大足县| 台中市| 额济纳旗| 孝昌县| 天全县| 普兰县| 沧州市| 清徐县| 西吉县| 吴桥县| 乌苏市| 克拉玛依市| 互助| 堆龙德庆县| 临朐县| 怀来县|