vue实现get请求
使用 axios 发送 GET 请求
在 Vue 项目中,通常使用 axios 库发送 HTTP 请求。以下是实现 GET 请求的步骤:
安装 axios 依赖:
npm install axios
在 Vue 组件中引入并使用:
import axios from 'axios';
export default {
methods: {
fetchData() {
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
}
}
使用 Vue 生命周期钩子发送 GET 请求
可以在 created 或 mounted 钩子中自动触发请求:
export default {
data() {
return {
items: []
};
},
created() {
axios.get('https://api.example.com/items')
.then(response => {
this.items = response.data;
});
}
}
带参数的 GET 请求
传递查询参数有两种方式:
通过 URL 直接拼接:
axios.get('https://api.example.com/search?keyword=vue')
通过 params 配置项:
axios.get('https://api.example.com/search', {
params: {
keyword: 'vue',
page: 1
}
})
使用 async/await 语法
更现代的异步处理方式:
export default {
methods: {
async loadUser() {
try {
const response = await axios.get('/api/user/123');
this.user = response.data;
} catch (error) {
console.error('Failed to load user:', error);
}
}
}
}
全局配置 axios
可以在 main.js 中设置默认配置:
import axios from 'axios';
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.timeout = 5000;
Vue.prototype.$http = axios;
之后在组件中可以直接使用:
this.$http.get('/data')
拦截器配置
添加请求和响应拦截器:
axios.interceptors.request.use(config => {
config.headers.Authorization = 'Bearer token';
return config;
});
axios.interceptors.response.use(
response => response,
error => {
if (error.response.status === 401) {
// 处理未授权情况
}
return Promise.reject(error);
}
);






