面试题答案
一键面试- 设计思路:
- 创建一个基础的网络请求封装函数,这个函数可以接收接口地址、请求方法、请求数据等参数。
- 在封装函数内部,将公共参数(如token)统一添加到请求数据或者请求头中。
- 可以使用
axios
库来进行实际的网络请求操作,因为它在Vue项目中使用广泛且功能强大。
- 示例代码:
首先安装
axios
(如果项目中还未安装):
然后在Vue项目中创建一个npm install axios
request.js
文件用于封装请求:
在Vue组件中使用这个封装的请求函数:import axios from 'axios'; // 假设从Vuex或者其他地方获取token,这里简单模拟 const getToken = () => 'your - token - value'; const request = (url, method = 'GET', data = {}) => { const config = { url, method, headers: { 'Content - Type': 'application/json' } }; if (method === 'GET') { // 处理GET请求参数 config.params = { ...data, token: getToken() }; } else { // 处理其他请求参数 config.data = { ...data, token: getToken() }; } return axios(config); }; export default request;
<template> <div> <button @click="fetchData">获取数据</button> </div> </template> <script> import request from './request.js'; export default { methods: { async fetchData() { try { const response = await request('/api/some - endpoint', 'GET', { otherParam: 'value' }); console.log(response.data); } catch (error) { console.error('请求出错', error); } } } }; </script>