【问题标题】:Trying to consume a .json but Vue-CLI doesn't find the file尝试使用 .json 但 Vue-CLI 找不到该文件
【发布时间】:2020-07-11 09:20:29
【问题描述】:

我有一个SQL database,我用json_encode 获取了它。我已将结果复制到 .json 以尝试使用 Vue-cli 来使用它。所以,我把文件放在assets,然后components,但在console,我总是有这个消息:

GET http://localhost:8080/assets/fetch.json 404 (Not Found)

另外,这是我在 App.vue 中放入的代码

<script>
export default {
  data() {
    return { dm: [], error: [] };
  },

  mounted() {
    this.$axios
      .get("views/fetch.json")
      .then(response => {
        this.dm = response.data;
      })
      .catch(e => {
        this.error.push(e);
      });
  }
};
</script>

并消费它:

  <tr v-for="(dm, index) in dm" :key="index">
    <td>{{ dm.id_dm }}</td>
  </tr>

【问题讨论】:

  • 这能回答你的问题吗? How to get a local file using axios?
  • 不是真的,我相信我的 Vue-CLI 上没有安装 axios。我正在寻找一种方法来检查这一点。

标签: api vue.js vue-cli


【解决方案1】:

我不确定您的项目结构是什么,但您是否尝试过使用import 语句直接导入文件,而不是像这样使用axios

<script>
 import data from "@/views/fetch.json"
</script>

然后,您可以将mounted() 中的data 分配给您可以循环访问的其他变量。

【讨论】:

  • 感谢您的回答。我已经这样做了:从“@/views/fetch.json”导入数据; export default { data() { return { data: [] } },但是现在显示有问题:mounted() axios.get("@/views/fetch.json").then(response => console .log(response)) 问题出在 axios 上。我删除了所有内容,然后重新安装了包括 axios 在内的所有内容,但仍然是同样的问题。我一直在谷歌上检查如何检查 axios 是否正确安装,但我没有找到任何东西。我快疯了。抱歉我的无知,我最近开始使用vuejs。
  • 同样,在这种情况下,我认为您不一定需要使用axios。在你导入 data 之后,就像我之前提到的那样,启动一个变量,如下所示:data() { return { myLocalData: null }; }, 然后在 mounted() 中将 data 分配给 myLocalData,如下所示:this.myLocalData = data 之后尝试 console.log(this.myLocalData) 看看是否数据已分配。如果是,那么您可以开始使用myLocalData。使用它在您的 HTML 模板中循环,就像您之前使用 v-for 所做的那样。我希望澄清。祝你好运!
猜你喜欢
  • 2018-12-12
  • 2017-08-20
  • 2019-06-12
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
相关资源
最近更新 更多