【问题标题】:Vue.js - How to use v-for in JSON array?Vue.js - 如何在 JSON 数组中使用 v-for?
【发布时间】:2021-05-17 11:12:32
【问题描述】:

我有来自服务器的 JSON 输出:

[
    {"id":"2","name":"Peter","age":"24"}, 
    {"id":"4","name":"Lucy","age":"18"},
]

现在我想将它与v-for 指令一起使用,但它对我不起作用。

这是我的导出默认值:

data () {
    return {
        info: {}
    }
},

mounted () {
    axios
      .get('http://localhost:4000/fetch.php/')
      .then(response => (this.info = response.data))
},

现在如果我想显示信息的输出,它工作得很好{{ info }}

但我需要使用v-for 指令并且只显示名称。

<p v-if="info.name">{{ info.name }}</p>

但它不起作用,唯一起作用的是:{{ info[0].name }}

【问题讨论】:

    标签: javascript arrays json vue.js


    【解决方案1】:

    您不能像这样直接读取name 属性:info.name。因为输出是一个对象数组而不是单个对象。

    data () {
        return {
            info: [], // make this an empty array
        }
    },
    mounted () {
        axios
            .get('http://localhost:4000/fetch.php/')
            .then(response => (this.info = response.data))
    },
    

    然后,您可以使用 v-for 指令在模板中呈现 info 数组:

    <ul v-if="info.length">
        <li v-for="item in info" :key="item.id">{{ item.name }}</li>
    </ul>
    

    阅读更多关于List Rendering in Vue的信息。

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 1970-01-01
      • 2020-11-29
      • 2018-01-21
      • 2020-11-07
      • 2021-05-10
      • 2016-11-16
      • 2018-01-09
      • 2019-02-08
      相关资源
      最近更新 更多