在 Nuxt 项目中使用 Axios 进行网络请求有两种常用方式:一是直接安装 Axios 并全局配置,二是使用 Nuxt 官方推荐的 @nuxtjs/axios
模块(更便捷)。以下是详细步骤:
方法一:使用官方推荐的 @nuxtjs/axios
模块(推荐)
1. 安装依赖
bash
npm install @nuxtjs/axios --save
# 或
yarn add @nuxtjs/axios
2. 在 nuxt.config.js
中配置
javascript
export default {
modules: [
'@nuxtjs/axios', // 引入模块
],
axios: {
// 配置基础URL(可选)
baseURL: 'https://api.example.com', // 后端API的基础路径
// 其他配置(如超时时间)
timeout: 10000,
// 允许跨域(根据需求配置)
credentials: true
}
}
3. 在组件/页面中使用
通过 this.$axios
调用,支持在 asyncData
、fetch
、methods
等场景使用:
vue
<template>
<div>
<h1>{{ post.title }}</h1>
<p>{{ post.content }}</p>
</div>
</template>
<script>
export default {
// 服务端/客户端获取数据(页面渲染前执行)
async asyncData({ $axios }) {
try {
const res = await $axios.get('/posts/1') // 基于baseURL的相对路径
return { post: res.data } // 直接返回数据给页面
} catch (error) {
console.error('请求失败:', error)
return { post: null }
}
},
// 在方法中使用(客户端执行)
methods: {
async fetchMoreData() {
try {
const res = await this.$axios.post('/comments', { content: 'Hello' })
console.log('提交成功:', res.data)
} catch (error) {
console.error('提交失败:', error)
}
}
}
}
</script>
方法二:直接使用 Axios(手动配置)
1. 安装 Axios
bash
npm install axios --save
# 或
yarn add axios
2. 创建 Axios 实例(推荐)
在 plugins
目录下创建 axios.js
:
javascript
// plugins/axios.js
import axios from 'axios'
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000
})
// 请求拦截器(可选)
instance.interceptors.request.use(
config => {
// 可添加token等逻辑
return config
},
error => Promise.reject(error)
)
// 响应拦截器(可选)
instance.interceptors.response.use(
response => response.data,
error => Promise.reject(error)
)
export default instance
3. 在 nuxt.config.js
中注册插件
javascript
export default {
plugins: [
'~/plugins/axios' // 注册插件
]
}
4. 在组件中使用
vue
<script>
import axios from '~/plugins/axios' // 导入实例
export default {
async asyncData() {
const post = await axios.get('/posts/1')
return { post }
}
}
</script>
关键注意事项
-
服务端 vs 客户端:
asyncData
和fetch
中的请求在服务端执行(首屏)或客户端路由跳转时执行。methods
中的请求仅在客户端执行。
-
错误处理 :务必使用
try/catch
捕获异常,避免请求失败导致页面崩溃。 -
环境变量 :建议将
baseURL
等配置放在.env
文件中,通过process.env
读取,区分开发/生产环境。
通过上述方法,即可在 Nuxt 中便捷地使用 Axios 进行网络请求,推荐优先使用 @nuxtjs/axios
模块,它与 Nuxt 生态更契合,支持自动注入和服务端适配。