others - Javascript - vue JS返回 [__ob__: Observer] data instead of my array of objects

我已经创建了一个页面,用API调用从数据库获取所有数据,我用Postman测试过了,我得到了正确的JSON。

这就是我得到

 

[__ob__: Observer]


length: 0


__ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}


__proto__: Array



这就是我想要

 

(140) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]


[0 … 99]


[100 … 139]


length: 140


__ob__: Observer {value: Array(140), dep: Dep, vmCount: 0}


__proto__: Array



这是我的Vue模板file:

 

<template>


 <div>


 <h2>Pigeons in the racing loft</h2>


 <div class= "card-content m-b-20" v-for= "pigeon in pigeons" v-bind:key= "pigeon.id"> 


 <h3>{{ pigeon.id }}</h3>


 </div>


 </div>


</template>



<script>


export default {


 data(){


 return{


 pigeons: [],


 pigeon: {


 id: '',


 sex: '',


 color_id: '',


 pattern_id: '',


 user_id: '',


 loft_id: '',


 country: '',


 experience: '',


 form: '',


 fatique: ''


 },


 pigeon_id: ''


 }


 },


 created(){


 this.fetchPigeons();


 console.log(this.pigeons);//Here I got the observer data instead my array


 },



 methods: {


 fetchPigeons(){


 fetch('api/racingloft')


 . then(res => res.json())


 . then(res => {


 console.log(res.data);//Here I get what I need


 this.pigeons = res.data;


 })


 }


 }


}


</script>



我也试图用axios来做,但是,它给了我同样的事情,当我从方法中控制它时,它会提供我的数据,但是,除此之外,它什么都没有给出。

时间:

因为Vuejs将数据中的每项转换为可以观察到的东西,所以,如果你把console log在数据中就有意义了,输出将被封装到观察者中。

要对数据有更好的了解,我建议你安装Vue开发工具, https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en

你应该等待获取完成后再返回结果。

 

created(){


 this.fetchPigeons().then(() => console.log(this.pigeons));


},



这样做的方式是同步记录结果,所以,在获取完成之前执行它。

编辑:就像@barbsan在他下面的评论中指出的,fetchPigeons需要为then返回一个Promise 。 fetch返回一个Promise所以,你只需要在fetchPigeons中返回fetch

 

fetchPigeons(){


 return fetch('api/racingloft')


 . then(res => res.json())


 . then(res => {


 console.log(res.data);//Here I get what I need


 this.pigeons = res.data;


 })


}



也可以尝试:

 

var parsedobj = JSON.parse(JSON.stringify(obj))


console.log(parsedobj)



当数据存在时,可以使用v-if指令来呈现该组件。

 

<h3 v-if= "pigeons.length> 0"> {{ pigeon.id }}</h3>



...