Vue3+Axios访问单条数据时出现404(Not Found)问题求助
Vue3 详情页无法根据ID展示单条数据问题
我开发了一个Vue3小型应用,可从本地JSON文件读取数据并展示列表,点击列表项可跳转至详情页查看完整数据。目前列表展示及跳转功能正常,但无法展示对应ID的单条数据,相关代码如下:
路由文件 router/index.js
... const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: 'Ndas', component: Ndas }, { path: '/nda/:id', name: 'NdaDetails', component: NdaDetails, props: true } ] }) ...
列表页 views/Ndas.vue(功能正常)
<template> <main> <h1>NDAS</h1> <div v-if="loading">Loading...</div> <div v-for="nda in ndas" :key="nda.id"> <router-link :to="{ name: 'NdaDetails', params: { id: nda.id }}"> <h2>{{ nda.user_signature }}</h2> </router-link> </div> </main> </template> <script> import axios from "axios"; export default { data() { return { loading: true, ndas: [] } }, mounted () { this.loading = true; axios .get('../../data/data.json') .then(response => (this.ndas = response.data)) .catch(error => console.log(error)) .finally(() => this.loading = false) }, } </script>
详情页 views/NdaDetails.vue(无法正常工作)
<template> <div> <div v-if="nda"> <h1>NDA's Detail Page</h1> <p>The job title is {{ nda.user_signature }}</p> </div> </div> </template> <script> import axios from "axios"; export default { props: ['id'], data() { return { nda: {} } }, async created() { try { const res = await axios.get('../../data/data.json/'+this.id); this.nda = res.data; } catch (error) { console.log(error); } }, } </script>
报错截图

问题根源
你在详情页里尝试通过 ../../data/data.json/'+this.id 请求单条数据,但本地JSON文件是完整的数组文件,无法通过URL拼接ID的方式获取单条数据,这会请求一个不存在的文件,导致返回404错误。
修复方案
方案一:读取完整JSON后筛选对应ID数据
修改 NdaDetails.vue 代码,先读取整个JSON文件,再根据传入的id筛选对应数据:
<template> <div> <div v-if="nda"> <h1>NDA详情页</h1> <p>用户签名:{{ nda.user_signature }}</p> </div> <div v-else>未找到对应数据</div> </div> </template> <script> import axios from "axios"; export default { props: ['id'], data() { return { nda: null } }, async created() { try { const res = await axios.get('../../data/data.json'); // 注意id可能为字符串类型,转换类型匹配数据中的id this.nda = res.data.find(item => item.id == this.id); } catch (error) { console.log(error); } }, } </script>
方案二(可选):拆分JSON为单个文件(适合大数据量)
如果数据量较大,不想每次加载整个数组,可将每条NDA数据单独存为data/nda-1.json、data/nda-2.json这类文件,再修改请求路径:
const res = await axios.get(`../../data/nda-${this.id}.json`); this.nda = res.data;
内容的提问来源于stack exchange,提问作者Charles Smith
相关产品推荐
相关产品推荐

