简体   繁体   English

Vue.js数组推送

[英]Vuejs array push

I'm receiving array of objects from backend in below format. 我正在从后端以以下格式接收对象数组。 I am trying to get this data and push it into a JavaScript array so that I can use them later on based on my needs. 我正在尝试获取此数据并将其推入JavaScript数组,以便以后可以根据需要使用它们。

[
    {
    id: 1,
    name: "Dr. Darrin Frami III",
    email: "darrin67@example.com",
    address: "42568 Cameron Cove Fritschborough, MA 86432-0749",

    },
]

Here is my vuejs code: 这是我的vuejs代码:

<script>
    export default {
      data(){
        return {
          fakeUsers: [],
          fakeUser: {id: '', name: '', email: ''},
        } 
      },
      methods:{

      },
        mounted() {
            var route = '/get-users';
            this.$http.get(route).then((response)=>{
              for (var i = 0; i < response.data.length; i++) {
                 this.fakeUser.id = response.data[i].id;
                 this.fakeUser.name = response.data[i].name;
                 this.fakeUser.email = response.data[i].email;
                 this.fakeUsers.push(this.fakeUser);
              }

            });
            console.log(this.fakeUsers);
            console.log(this.fakeUsers[0]);
        }
    }
</script>

the vue-dev tool result: vue-dev工具结果:

在此处输入图片说明

Output of the line console.log(this.fakeUsers); 该行的输出console.log(this.fakeUsers); is [__ob__: Observer] . [__ob__: Observer] Shouldn't it print something like [Array[10]] ? 它不应该打印类似[Array[10]]吗?

Output of the line console.log(this.fakeUsers[0]); console.log(this.fakeUsers[0]); is undefined , and I can't figure out why. undefined ,我不知道为什么。

$http() creates an async ajax call, so the code in then() is executed after the console command after it. $ HTTP()创建一个异步AJAX调用,所以在代码then()之后它在控制台命令之后被执行。

Simple solution: put the console commands into the function in .then() as well. 简单的解决方案:将控制台命令也放入.then()的函数中。

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

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