从vue js中的json nonarray fornmat获取值(后端使用laravel)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从vue js中的json nonarray fornmat获取值(后端使用laravel)相关的知识,希望对你有一定的参考价值。

如果我使用邮递员数据来获取个人资料,例如这样

{
  "status": "success",
  "status_code": 200,
  "message": "OK",
  "data": {
    "id": 2,
    "name": "ahsan",
    "email": "ahsan@gmail.com",
    "email_verified_at": "2019-12-24 08:40:35",
    "password": "$2y$10$cr3bRfqZ3Fp3uxnqgInNCugwAdSNury3Nsn6GMl9T36kxT.36GmzS",
    "remember_token": null,
    "created_at": "2019-12-24 08:40:35",
    "updated_at": "2019-12-24 08:40:35",
    "member_pin": "xxxxxxx",
    "google2fa_secret": null,
    "google_2fa enum ""Y"",""N"",": "N",
    "reff_id": ""
  }
}

如何获得价值?因为数据不是数组格式?

我尝试使用v-,因为所有数据都不会像列表数组格式那样呈现

答案

您可以使用Object.keys获取所有键作为数组,并使用v-for获取值

var app = new Vue({
  el: '#app',
  data:{
    test:{
      "status": "success",
      "status_code": 200,
      "message": "OK",
      "data": {
        "id": 2,
        "name": "ahsan",
        "email": "ahsan@gmail.com",
        "email_verified_at": "2019-12-24 08:40:35",
        "password": "$2y$10$cr3bRfqZ3Fp3uxnqgInNCugwAdSNury3Nsn6GMl9T36kxT.36GmzS",
        "remember_token": null,
        "created_at": "2019-12-24 08:40:35",
        "updated_at": "2019-12-24 08:40:35",
        "member_pin": "xxxxxxx",
        "google2fa_secret": null,
        "google_2fa enum ""Y"",""N"",": "N",
        "reff_id": ""
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
<div v-for="key in Object.keys(test.data)"><strong>{{key}}</strong> : {{test.data[key]}}</div>
</div>
另一答案

在您的情况下,您只需要在user之类的data属性中存储响应数据,然后只需在html模板中编写以下代码即可:

{{ user.email }}

除非您有多个用户,否则可能不需要v-for

将以下组件作为示例(适用于多个用户)。

<template>
    <div>
        <h1>Users</h1>
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">Email</th>
                    <th scope="col">First Name</th>
                    <th scope="col">Last Name</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="user in users" :key="user.email">
                    <td> {{ user.email }} </td>
                    <td>{{ user.first_name }}</td>
                    <td>{{ user.last_name }}</td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
export default {
    data() {
        return {
            users:null,
        }
    },
    created() {
        this.getUsers(); // Will make Laravel API call
    },
    methods: {
        getUsers(){
            this.axios.get("https://reqres.in/api/users").then((response) => {
                this.users = response.data.data;
            });
        }
    }
}
</script>

以上是关于从vue js中的json nonarray fornmat获取值(后端使用laravel)的主要内容,如果未能解决你的问题,请参考以下文章