【问题标题】:reading data from a JSON file into Vue application从 JSON 文件读取数据到 Vue 应用程序
【发布时间】:2020-09-09 19:07:52
【问题描述】:

我有一个包含对象列表的 json 文件

[
    {
        "name": "Alkaline",
        "description": "Basic as opposed to acidic; high pH."
    },
    {
        "name": "Alkaloids",
        "description": "Water-insoluble, nitrogen containing
    }...
]

我需要将此文件读入我的 vuejs 应用程序并循环显示所有显示名称和描述的数据。

我遇到的主要问题实际上是访问 json。

当我像这样进行导入时

import json from './glossary.json';

var app = new Vue({
    el: '#app'...

我收到一个错误提示

Uncaught SyntaxError: Cannot use import statement outside a module

数据是静态的,所以我不会从服务器获取它,而且我有大约 100 个对象,所以我希望从另一个文件中读取它,而不是在我的应用程序中硬编码。

非常感谢任何帮助

【问题讨论】:

    标签: json vue.js


    【解决方案1】:

    这不是 vue 的错误,也不是 json 的错误,而是 javascript 模块的错误。在您的 html 中导入时,您需要将脚本声明为模块 <script type="module" src="path/to/script.js"></script>

    但是既然你用的是vue,那就去学习单文件组件吧。它会为您处理,然后您只需

    <script>
    import yourFile from './path/to/file'
    // .. you can use it here
    export default {
      // .. and here
      // this is the same as the object you put into new Vue
    }
    </script>
    
    <template>
      <div id="el">
        <p>Your component's html goes here.</p>
        <p>It's auto mounted on the root of the template,
        so no need to even declare it above</p>
      </div>
    </template>
    

    See more info on single file components on official docs here.(页面顶部还有一个不错的 scrimba 视频!)

    【讨论】:

      猜你喜欢
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多