javascript - 运行NUXT.js和Axios时如何避免代码重复?

标签 javascript vue.js axios nuxt.js

введите сюда описание изображения

如果类似的代码(如示例中所示)在不同的组件中重复,但我在函数参数中传递的名称略有不同

有哪些选项可以将代码单独放在某处,然后使用自定义参数将其引入我的组件中? (每个组件单独)

我应该通过插件来做到这一点吗? 如果是这样,那么我如何在组件上实现单独必需的参数+如何仅在这些组件上连接插件而不是在其他地方?

最佳答案

对于 axios 调用,您可以创建一个函数或类并每次导入它

类似services/axios

import axios from 'axios';


const axiosInstance = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    headers: {
        'Access-Control-Allow-Origin': '*',
        accept: 'Accept: application/json',
    },
});

export default axiosInstance;

然后在utils/requests

import axiosInstance from '@/services/axios';

const apiRequest = async (axiosConfig) => {
  try {
      const response = await axiosInstance(axiosConfig);
      return {
        success: true,
        data: response.data.data || response.data;
      }
  } catch (error) {
      if (error.response) {
       error = error.response
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
       error = error.request
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
       error = error.message
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
      return {
        success: false,
        error
      }
  }
};

export const getRequest = async (url) =>
    await apiRequest({
        method: 'GET',
        url,
    });

export const postRequest = async(url, requestBody) =>
    await apiRequest({
        method: 'POST',
        url,
        data: requestBody
    });

然后在组件中导入 getRequest 和 postRequest 方法

组件.vue

import { getRequest, postRequest } from '@/utils/requests';

 
const response = await postRequest('/url', requestBody);
 
if (response.success) {
   // do stuff on success
 } else {
  // error message
 }

关于javascript - 运行NUXT.js和Axios时如何避免代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63207552/

相关文章:

javascript - 任何人都可以从子 iframe 关闭由 Jquery 插件 bPopup 生成的弹出窗口?

javascript - 请求有效负载 - 可选的数据发送

javascript - ReactJs如何发布时间

javascript - Axios 和 Fetch 有什么区别?

java - DNODE 作为一种让 Java 调用 NodeJS 函数的方法?

javascript - 限制从 CheckboxList 中选择的选项数量

javascript - Handlebars 范围问题 : Can't access template variable from embedded `each`

firebase - 如何在 Vue.js 中获取新创建的 Firestore 文档的 ID?

vue.js - vue子组件如何使用$refs实现焦点转移?

css - Vue - 使用大括号语法在 css 中绑定(bind)数据