简体   繁体   English

Vuejs来自API的嵌套JSON数据未显示

[英]Vuejs nested JSON data from API not displaying

When getting json data from API,Im unable to access nested ppts. 从API获取json数据时,无法访问嵌套的ppts。

My Vue component 我的Vue组件

var profileComponent = {
    data : function() {
        return {
            isError : false,
            loading : true,
            users : null,
            activeUser : '',                
        }
    },
    mounted() {
        axios
        .get('https://jsonplaceholder.typicode.com/users')
        .then(response => (this.users = response.data))
        .catch(error => {console.log(error);this.isError = true})
        .finally(() => {console.log('GET request from users');this.loading = false})
     },
    template : `
    <div class="profile">
        <div v-if="isError">
            <h3>There was an error</h3>
        </div>
        <div v-else-if='isLoading'>
        Loading
        </div>
        <div v-else>   
                <select v-model="activeUser">
                    <option v-for="user in users" v-bind:value="user">{{ user.name }}</option>
                </select>          
        </div>
        <div class="temp">
            <p>{{ activeUser.address.street }}</p>
        </div>
    </div>
`}

This Doesnt work but when I change {{ activeUser.address.street }} to {{ activeUser.address }} it starts working.Note the users object from jsonplaceholder website contains street ppt as well.What am I missing? 这不起作用,但是当我将{{ activeUser.address.street }}更改为{{ activeUser.address }}它开始工作。请注意jsonplaceholder网站中的users对象也包含street ppt。我缺少什么?

activeUser is an empty string by default so you access activeUser.address it is undefined and if you use activeUser.address.street it gives an error For resolving this issue you can use activeUser默认情况下为空字符串,因此您访问activeUser.address时未定义,如果使用activeUser.address.street则会产生错误。要解决此问题,可以使用

<p>{{ (activeUser && activeUser.address)? activeUser.address.street : ''}}</p>  

instead of simple 而不是简单

<p>{{ activeUser.address.street }}</p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM