如何在vue.js应用程序中访问外部json文件对象 [英] How to acces external json file objects in vue.js app

查看:539
本文介绍了如何在vue.js应用程序中访问外部json文件对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问 vue.js 应用中的 JSON 对象我是新来的

How to access JSON objects in the vue.js app I am new in this

import json from './json/data.json'

JSON文件已加载,现在我必须访问其中的对象

the JSON file is loaded and now I have to access the objects within it

推荐答案

只需将导入分配给数据属性

Just assign the import to a data property

<script>
      import json from './json/data.json'
      export default{
          data(){
              return{
                  myJson: json
              }
          }
      }
</script>

然后循环遍历 myJson 属性模板使用 v-for

then loop through the myJson property in your template using v-for

<template>
    <div>
        <div v-for="data in myJson">{{data}}</div>
    </div>
</template>

注意

如果你要导入的对象是静态的,即没有改变,那么将它分配给数据属性是没有意义的,因为它不需要被动。

If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.

Vue将 data 选项中的所有属性转换为getter / setter,以使属性成为被动的。因此,为不会改变的数据设置getter / setter是不必要的和开销。请参阅深度反应性

Vue converts all the properties in the data option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.

因此,您可以按如下方式创建自定义选项:

So you can create a custom option as follows:

<script>
          import MY_JSON from './json/data.json'
          export default{
              //custom option named myJson
                 myJson: MY_JSON
          }
    </script>

然后使用 $ options

<template>
        <div>
            <div v-for="data in $options.myJson">{{data}}</div>
        </div>
    </template>

这篇关于如何在vue.js应用程序中访问外部json文件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆