【问题标题】:Getting data with Axios from .json in a vue loop在 vue 循环中使用 Axios 从 .json 获取数据
【发布时间】:2021-11-02 16:25:36
【问题描述】:

在我的导航中,我想插入来自我的 CMS 的链接。我正在使用 Axios。我的导航是 Vue。如何将 JSON 文件中的数据获取到 const 中?

只要知道我是否需要在 Axios 或 Vue 中搜索解决方案也会有很大帮助。

import axios from "axios";

const exhibitions = [
    {
    name: "Exhibition 1",
    description: "Info 1",
    href: "#",
    },

    {
    name: "Exhibition 2",
    description: "Info 2",
    href: "#",
    },    
];

我的导出默认值:

export default {
  name: "item",
  data() {
    return {
      info: null,
    };
  },
  mounted() {
    axios
      .get("http://localhost:8000/posts.json")
      .then((response) => (this.info = response));
  },

posts.json

{
"data":
    [{
    "id":1028,
    "title":"Exhibition 1",
    "slug":"exhibition-2009",
    "url":"http://localhost:8000/exhibitions/exhibition-2009"
    },
    {
    "id":905,
    "title":"Exhibition 2",
    "slug":"exhibition-2006",
    "url":"http://localhost:8000/exhibitions/exhibition-2006"
    }],
"meta":
    {
    "pagination":
    {
    "total":2,
    "count":2,
    "per_page":100,
    "current_page":1,
    "total_pages":1,
    "links":{}
     }
     }
 }

【问题讨论】:

标签: json vue.js axios tailwind-ui


【解决方案1】:

“将数据从 JSON 中获取到 const”是什么意思??

提醒一下,不能修改常量。

根据您的评论,我猜您想将从您的 json 文件中获取的数据存储到 info 变量。然后,在导航栏中呈现您的链接。

mounted() {
    axios
       .get("http://localhost:8000/posts.json")
       .then((response) => (this.info = response));
}

安装组件后,您将使用 Axios 从文件中获取 JSON 数据。当承诺被接受时,您将响应数据存储到this.info。将数据放入该变量后,您就可以渲染所有内容⬇️

VueJS 中有一个名为 v-for 的列表渲染指令。您可以使用它来呈现导航栏的所有链接。

<ul id="navigation-bar">
    <li v-for="i in info">
        <a href="{{ i.url }}"> {{ i.title }} </a>
    </li>
</ul>

【讨论】:

  • 请更好地解释您的解决方案How do I write a good answer?
  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
  • 感谢有关常量的信息。我明白并会尝试。
  • 其实你想要达到什么目的? ?
  • @jiahui-chen 我想将 .json 文件(从 CraftCMS 导出)中的 2 个信息(标题和 URL)加载到我的 vue.js 导航中。
猜你喜欢
  • 2023-03-23
  • 2021-05-26
  • 2019-07-03
  • 2020-05-15
  • 2021-09-22
  • 2021-07-22
  • 2018-01-17
  • 1970-01-01
  • 2020-09-27
相关资源
最近更新 更多