如果类似的代码(如示例中所示)在不同的组件中重复,但我在函数参数中传递的名称略有不同
有哪些选项可以将代码单独放在某处,然后使用自定义参数将其引入我的组件中? (每个组件单独)
我应该通过插件来做到这一点吗? 如果是这样,那么我如何在组件上实现单独必需的参数+如何仅在这些组件上连接插件而不是在其他地方?
最佳答案
对于 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/