欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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";//模擬,并非真實(shí)地址
      } 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)文章

  • Vue3?props的使用示例詳解

    Vue3?props的使用示例詳解

    這篇文章主要介紹了Vue3?props的使用詳解,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-10-10
  • Vue子組件關(guān)閉后調(diào)用刷新父組件的實(shí)現(xiàn)

    Vue子組件關(guān)閉后調(diào)用刷新父組件的實(shí)現(xiàn)

    這篇文章主要介紹了Vue子組件關(guān)閉后調(diào)用刷新父組件的實(shí)現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Vue3監(jiān)聽屬性與Computed的區(qū)別詳解

    Vue3監(jiān)聽屬性與Computed的區(qū)別詳解

    在 Vue 3 中,watch 和 computed 都是非常重要的概念,它們都可以用于觀察和響應(yīng)數(shù)據(jù)的變化,但在使用場景和原理上存在明顯的區(qū)別,本文將詳細(xì)解析 Vue 3 中監(jiān)聽屬性 (watch) 和計算屬性 (computed) 的區(qū)別,需要的朋友可以參考下
    2024-02-02
  • uni-app 使用編輯器創(chuàng)建vue3 項目并且運(yùn)行的操作方法

    uni-app 使用編輯器創(chuàng)建vue3 項目并且運(yùn)行的操作方法

    這篇文章主要介紹了uni-app 使用編輯器創(chuàng)建vue3 項目并且運(yùn)行的操作方法,目前uniapp 創(chuàng)建的vue3支持 vue3.0 -- 3.2版本 也就是說setup語法糖也是支持的,需要的朋友可以參考下
    2023-01-01
  • Vue項目安裝使用moment.js方式

    Vue項目安裝使用moment.js方式

    文章介紹了如何在Vue項目中安裝和使用moment.js,包括安裝步驟、導(dǎo)入方法、漢化設(shè)置以及在Vue實(shí)例中使用moment.js進(jìn)行日期處理
    2024-11-11
  • vue登錄頁實(shí)現(xiàn)使用cookie記住7天密碼功能的方法

    vue登錄頁實(shí)現(xiàn)使用cookie記住7天密碼功能的方法

    這篇文章主要介紹了vue登錄頁實(shí)現(xiàn)使用cookie記住7天密碼功能的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • vue單個組件實(shí)現(xiàn)無限層級多選菜單功能

    vue單個組件實(shí)現(xiàn)無限層級多選菜單功能

    這篇文章主要介紹了vue單個組件實(shí)現(xiàn)無限層級多選菜單的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2018-04-04
  • MVVM模型在Vue中的使用詳解

    MVVM模型在Vue中的使用詳解

    MVVM模型主要是為了分離視圖(View)和模型(Model),其優(yōu)點(diǎn)為:低耦合、可重用性、獨(dú)立開發(fā)以及可測試,視圖和模型分離的特點(diǎn)給了 Vue 很大的啟發(fā),這篇文章主要介紹了MVVM模型在Vue中的使用,需要的朋友可以參考下
    2022-11-11
  • Vue3.3?+?TS4構(gòu)建實(shí)現(xiàn)ElementPlus功能的組件庫示例

    Vue3.3?+?TS4構(gòu)建實(shí)現(xiàn)ElementPlus功能的組件庫示例

    Vue.js?是目前最盛行的前端框架之一,而?TypeScript?則是一種靜態(tài)類型言語,它能夠讓開發(fā)人員在編寫代碼時愈加平安和高效,本文將引見如何運(yùn)用?Vue.js?3.3?和?TypeScript?4?構(gòu)建一個自主打造媲美?ElementPlus?的組件庫
    2023-10-10
  • Vue如何通過瀏覽器控制臺查看全局data值

    Vue如何通過瀏覽器控制臺查看全局data值

    在寫vue項目時想到一個問題,項目里面的文件都是一個個的組件,如何在控制臺中修改,查看組件data里的值呢,下面這篇文章主要給大家介紹了關(guān)于Vue如何通過瀏覽器控制臺查看全局data值的相關(guān)資料,需要的朋友可以參考下
    2023-04-04

最新評論