Vue.js 如何获取 JSON 数据:从基础到实践的完整指南
在现代前端开发中,与后端 API 进行数据交互是必不可少的环节,而 JSON 作为轻量级的数据交换格式,被广泛使用,Vue.js 作为流行的前端框架,提供了多种方式来获取和处理 JSON 数据,本文将详细介绍在 Vue.js 项目中获取 JSON 数据的各种方法、最佳实践以及常见问题的解决方案。
使用 Axios 发起 HTTP 请求获取 JSON
Axios 是一个基于 Promise 的 HTTP 客户端,广泛用于浏览器和 Node.js 中,是 Vue.js 项目中获取 JSON 数据的首选工具。
安装 Axios
需要通过 npm 或 yarn 安装 Axios:
npm install axios # 或 yarn add axios
在 Vue 组件中使用 Axios
在 Vue 组件中,可以通过 import 引入 Axios,然后使用其 get 或 post 等方法发起请求。
<template>
<div>
<h1>用户列表</h1>
<ul v-if="users.length">
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
<p v-else>加载中...</p>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
users: []
};
},
mounted() {
this.fetchUsers();
},
methods: {
async fetchUsers() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
this.users = response.data;
} catch (error) {
console.error('获取用户数据失败:', error);
// 可以在这里添加错误处理逻辑,比如显示错误信息
}
}
}
};
</script>
说明:
mounted()钩子在组件挂载后调用,适合发起初始数据请求。async/await用于处理异步请求,使代码更易读。response.data包含了服务器返回的 JSON 数据。- 使用
try...catch捕获请求过程中可能发生的错误。
配置 Axios 全局实例
为了避免在多个组件中重复配置 Axios,可以创建一个全局实例:
// src/utils/api.js
import axios from 'axios';
const api = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 5000 // 请求超时时间
});
export default api;
然后在组件中使用:
import api from '@/utils/api';
// 在 methods 中
async fetchUsers() {
try {
const response = await api.get('/users');
this.users = response.data;
} catch (error) {
console.error(error);
}
}
使用 Vue Resource 获取 JSON(较少使用)
Vue Resource 是 Vue.js 官方推荐的 HTTP 客户端,但在 Vue 2.6 之后不再推荐,更推荐使用 Axios,但如果项目仍在使用,可以这样:
安装 Vue Resource
npm install vue-resource
在 Vue 中使用
import Vue from 'vue';
import VueResource from 'vue-resource';
Vue.use(VueResource);
export default {
data() {
return {
users: []
};
},
mounted() {
this.$http.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
this.users = response.body;
}, error => {
console.error('获取用户数据失败:', error);
});
}
};
说明:
- Vue Resource 的 API 风格与 Axios 不同,使用
this.$http发起请求。 response.body包含 JSON 数据。
使用 Fetch API 原生获取 JSON
Fetch API 是浏览器内置的接口,无需额外安装,但处理错误和异步的方式与 Axios 略有不同。
<template>
<div>
<h1>用户列表</h1>
<ul v-if="users.length">
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
<p v-else>加载中...</p>
</div>
</template>
<script>
export default {
data() {
return {
users: []
};
},
mounted() {
this.fetchUsers();
},
methods: {
async fetchUsers() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
this.users = data;
} catch (error) {
console.error('获取用户数据失败:', error);
}
}
}
};
</script>
说明:
- Fetch API 默认不会拒绝 HTTP 状态码(如 404、500),需要手动检查
response.ok。 response.json()是异步方法,需要await来获取解析后的 JSON 数据。
从本地 JSON 文件获取数据
有时,我们需要从本地的 JSON 文件中加载数据,例如静态配置或模拟数据。
在 public 目录下放置 JSON 文件
将 JSON 文件(如 data.json)放在 public 目录下,这样可以通过绝对路径直接访问。
// public/data.json
{
"users": [
{ "id": 1, "name": "John Doe" },
{ "id": 2, "name": "Jane Smith" }
]
}
在 Vue 组件中获取
export default {
data() {
return {
users: []
};
},
mounted() {
this.fetchLocalData();
},
methods: {
async fetchLocalData() {
try {
const response = await fetch('/data.json');
const data = await response.json();
this.users = data.users;
} catch (error) {
console.error('获取本地数据失败:', error);
}
}
}
};
注意:
- 如果使用 Vue CLI 或 Vite 等构建工具,本地 JSON 文件也可以放在
src/assets目录下,但需要通过import方式引入(适用于构建时静态资源)。
import jsonData from '@/assets/data.json';
export default {
data() {
return {
users: jsonData.users
};
}
};
处理异步数据加载状态
在实际应用中,数据加载需要时间,通常会显示加载状态或错误信息。
<template>
<div>
<h1>用户列表</h1>
<div v-if="loading">加载中...</div>
<div v-else-if="error">{{ error }}</div>
<ul v-else-if="users.length">
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
<div v-else>暂无数据</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
users: [],
loading: false,
error: null
};
},
mounted() {
this.fetchUsers();
},
methods: {
async fetchUsers() {
this.loading = true;
this.error = null;
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
this.users = response.data;
} catch (error) {
this.error = '获取用户数据失败,请稍后重试。';
console.error(error);
} finally {
this.loading = false;
}
}
}
};
</script>
使用 Vuex 管理全局 JSON 数据
如果多个组件需要共享同一份数据,可以使用 Vuex 进行状态管理。
创建 Vuex Store
// src/store/modules/users.js
import axios from 'axios';
const state = {
users: [],
loading: false,
error: null
};
const mutations = {
SET_USERS(state, users) {
state.users = users;
},
SET_LOADING(state, loading) {
state.loading = loading;
},
SET_ERROR(state, error) {
state.error = error;
}
};
const actions = {
async fetchUsers({ commit }) {
commit('SET_LOADING', true);
commit('SET_ERROR', null);
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
commit('SET_USERS', response.data);
} catch (error) {
commit('SET_ERROR', '获取用户数据失败');
console.error(error);
} finally {
commit('SET_LOADING', false);
}
}
};
export default {
namespaced: true,
state,
mutations,
actions
};
在组件中使用 Vuex
<template>
<div>
<h1>用户列表</h1>
<div v-if="loading">加载中...</div>
<div v-else


还没有评论,来说两句吧...