vue项目用axios获取本地json

本文介绍如何在Vue项目中通过Axios获取并解析位于public目录下的本地JSON文件。利用Vue的生命周期钩子created,发送HTTP请求到指定路径,并处理响应数据。

vue项目用axios获取本地json

在这里插入图片描述

代码

<template>
  <div class="box"></div>
</template>

<script>

import axios from 'axios'

export default {
  name: "demo",
  created() {
    axios.get('/a.json').then(res => {  //此时相当于访问 http://localhost:8080/chinaData/100000.json

      let {data} = res.data
      console.log('data', data)
      this.total = data.total
      this.recordsList = data.records
    })
  }
}
</script>

<style scoped>

</style>

json文件放到public下
在这里插入图片描述

### 如何在 Vue 中使用 Axios 获取本地 JSON 数据 #### 创建静态资源目录 为了方便管理和访问,在 `src` 同级位置创建名为 `static` 的文件夹用于存储静态资源,比如 `data.json` 文件[^4]。 #### 安装 Axios 库 如果尚未安装 Axios,则可以通过 npm 或 yarn 来完成安装: ```bash npm install axios --save ``` 或者 ```bash yarn add axios ``` #### 修改 Vue 组件代码 下面是一个简单的例子展示了怎样在一个 Vue文件组件内利用 Axios 请求并处理来自本地服务器的 JSON 响应数据[^2]: ```html <template> <div class="box"> <!-- 展示获取到的数据 --> Total: {{ total }}<br/> Records List:<ul v-for="(record, index) in recordsList" :key="index"><li>{{ record }}</li></ul> </div> </template> <script> import axios from 'axios' export default { name: "Demo", data() { return { total: null, recordsList: [] } }, created() { axios.get('/static/a.json') // 路径指向 static 下面的 a.json 文件 .then(response => { const {total, records} = response.data; this.total = total; this.recordsList = records; }) .catch(error => console.error(`Error fetching json file ${error}`)); } } </script> <style scoped> /* 添加样式 */ .box { border: 1px solid black; padding: 10px; } </style> ``` 此段代码会在页面加载时自动发起 HTTP GET 请求去取得位于 `/static/a.json` 地址下的 JSON 文件内容,并把其中的信息赋给组件内的变量以便于后续操作和显示。注意这里假设了 `a.json` 文件结构中有 `total` 和 `records` 字段。 #### 解决可能出现的问题 当遇到请求返回 404 错误的情况时,可以尝试调整路径设置或确认 Webpack 配置是否正确解析了相对 URL 到实际物理地址映射关系;另外也要确保开发环境已经启动并且能够正常提供服务[^3]。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值