【问题标题】:Trying to load json through Vue Axios尝试通过 Vue Axios 加载 json
【发布时间】:2019-08-13 20:14:48
【问题描述】:

我正在尝试从名为 blogs.json 的 static 目录中包含一个本地 JSON 文件,其中包含大量博客。

我目前正在通过 Vue Axios 加载博客,这是我在 Nuxt JS 中包含的一个模块。

目前,从 json 文件加载博客非常好,但是在加载博客之前有明显的几毫秒延迟,我正在尝试找出一种更好的方法来加载 json 文件并填充 @ 987654324@数组列在data()内

这是我当前的代码:

<script>
import PageBanner from '~/components/PageBanner';

export default {
  head: {
    title: 'Site Title: Blog',
    meta: [
      { hid: 'description', name: 'description', content: 'Site description' }
    ]
  },
  components: {
    PageBanner
  },
  data () {
    return {
      blogs: [],
      isLoading: true
    }
  },
  created () {
    this.axios.get("/articles/blogs.json").then((response) => {
      this.blogs = response.data
      this.isLoading = false
    })
  }
}
</script>

这很好用,但我怎样才能修改它以更快地加载 json?

【问题讨论】:

  • 我相信你的 JSON 是本地数据,那么你不需要使用异步代码来获取数据。如果希望加载更快,可以直接用作变量。
  • 我对 nuxt.js 不太熟悉(因为我只使用 vue.js),但您可以查看文档,尤其是此处的中间件:nuxtjs.org/guide/routing#middleware
  • 我将如何实现这个?
  • 你的 blogs.json 文件有多大?

标签: json vue.js vuejs2 nuxt.js


【解决方案1】:

只需导入它,执行此操作,它应该可以正常工作:

<template>
    <div>
        <!-- There should be no delay -->
        {{blogs}} 
    </div>
<template>
<script>
import PageBanner from '~/components/PageBanner';

import blogsFromJson from '~/articles/blogs.json'; // Or wherever it is found

export default {
  head: {
    title: 'Site Title: Blog',
    meta: [
      { hid: 'description', name: 'description', content: 'Site description' }
    ]
  },
  components: {
    PageBanner
  },
  data () {
    return {
      blogs: blogsFromJson, // Just set it here
      isLoading: true
    }
  },
  /* No need for this anymore
  created () {
    this.axios.get("/articles/blogs.json").then((response) => {
      this.blogs = response.data
      this.isLoading = false
    })
  }
  */
}
</script>

【讨论】:

  • @RyanHolton 如果它对您有用,请将此答案标记为正确。谢谢!
猜你喜欢
  • 2022-11-22
  • 2021-12-27
  • 2018-08-07
  • 2013-09-02
  • 2021-09-10
  • 2015-10-13
  • 2021-07-03
  • 2018-06-18
  • 2019-09-10
相关资源
最近更新 更多