Javascript Vue JS 返回 [__ob__: Observer] 数据而不是我的对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52873516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:01:26  来源:igfitidea点击:

Vue JS returns [__ob__: Observer] data instead of my array of objects

javascriptarrayslaravelvue.jsaxios

提问by shawnest

I've created a page where I want to get all my data from the database with an API call, but I'm kinda new to VueJS and Javascript aswell and I don't know where I'm getting it wrong. I did test it with Postman and I get the correct JSON back.

我创建了一个页面,我想通过 API 调用从数据库中获取我的所有数据,但我对 VueJS 和 Javascript 也有点陌生,我不知道我哪里出错了。我确实用 Postman 对其进行了测试,并得到了正确的 JSON。

This is what I get:

这就是我得到的:

[__ob__: Observer]
length: 0
__ob__: Observer {value: Array(0), dep: Dep, vmCount: 0}
__proto__: Array

This is what I want:

这就是我要的:

(140) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
[0 … 99]
[100 … 139]
length: 140
__ob__: Observer {value: Array(140), dep: Dep, vmCount: 0}
__proto__: Array

Thats my Vue template file:

那是我的 Vue 模板文件:

<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>

I've tried to do it with axios aswell, but it gave me exactly the same thing. When I console it from the method it gives my data, but outside it just gives nothing.

我也试过用 axios 来做,但它给了我完全一样的东西。当我从方法中安慰它时,它给出了我的数据,但在它之外什么也没给出。

回答by guillim

Can also try this:

也可以试试这个:

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

It was brought by Evan You himself hereand more info on that here

它被带到埃文你自己在这里和更多的信息在这里

But waiting for the answer is a first step.

但等待答案是第一步。

回答by Kevin LE GOFF

This happens because Vue js convert every item in the data to something that can be observed. So it makes sense if you console log something in the data. The output will be something wrapped into an observer.

发生这种情况是因为 Vue js 将数据中的每个项目都转换为可以观察到的内容。因此,如果您通过控制台在数据中记录一些内容,这是有道理的。输出将是包裹在观察者中的东西。

To have a better vision on your data I suggest you to install the Vue dev tools. https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en

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

回答by mudin

Here is my solution:

这是我的解决方案:

add new method something like logto your $root component. App.vue's createdis recommended:

log向您的 $root 组件添加类似的新方法。App.vuecreated推荐:

this.$root.log = function log() {
  for (let i = 0; i < arguments.length; i += 1) {
    if (typeof (arguments[i]) === 'object') {
      try {
        arguments[i] = JSON.parse(JSON.stringify(arguments[i]));
      } catch (e) {
        console.error(e);
      }
    }
  }
  console.log(...arguments);
};

just call this.$root.log(this.pigeons)in your component.

只需调用this.$root.log(this.pigeons)您的组件。

My result:

我的结果:

BEFORE:

前:

enter image description here

在此处输入图片说明

AFTER:

后:

enter image description here

在此处输入图片说明

回答by Husam Ibrahim

You should probably wait for the fetch to finish then console.log the result ..

您可能应该等待获取完成然后 console.log 结果..

created(){
    this.fetchPigeons().then(() => console.log(this.pigeons));
},

The way you were doing it you were logging the result synchronously so it gets executed before the fetch is done.

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

Edit:Also as @barbsan pointed out in his comment below your fetchPigeonsneeds to return a promise for thento work. fetchreturns a promise so you just need to return fetch in fetchPigeons

编辑:正如@barbsan 在下面的评论中指出的那样,您fetchPigeons需要返回then工作承诺。fetch返回一个承诺,所以你只需要返回 fetch infetchPigeons

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;
    })
}

回答by Yahya

You can use v-ifdirective to render the component once the data is there.

v-if一旦数据存在,您就可以使用指令来呈现组件。

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

回答by ranjit0829

Thank you for all your suggestion. Things worked on my end by just using "const".

谢谢你的所有建议。仅使用“ const”就可以解决我的问题。

const cookieInfo = ToolCookieService.getToolNumbersFromCookie();

Thanks, Ranjit

谢谢,兰吉特

回答by Andre Ravazzi

As mentioned by Husam Ibrahim, you should wait the async fetch() function to resolve. Another approach could be use async/await in your function:

正如 Husam Ibrahim 所提到的,您应该等待 async fetch() 函数解析。另一种方法是在您的函数中使用 async/await:

methods: {
    async fetchPigeons(){
        await fetch('api/racingloft')
               .then(res => res.json())
               .then(res => {
                   console.log(res.data);
                   this.pigeons = res.data;
               })
    }
}

And then it should work:

然后它应该工作:

<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>

回答by Peter Pan

I got the same problem still stuck ...

我遇到了同样的问题仍然卡住了......

Wrote these according to Evan(Vue Author) JSON.parse(JSON.stringify(res.data)) method, But why can't normal data?

这些都是按照Evan(Vue Author) JSON.parse(JSON.stringify(res.data)) 方法写的,但是为什么不能正常数据呢?

  methods: {
    async getdata() {
      console.log(1);
      await axios.get(API).then((res) => {
          console.log(2);
          if (!this.dataList.length) {
            this.dataList = JSON.parse(JSON.stringify(res.data));
            console.log(3);
            console.log(res.data, 'res.data ');
            console.log(this.dataList, 'this.dataList')
            console.log('----------check-----------',JSON.parse(JSON.stringify(res.data)));
          }
        })
        .catch(err => {
          console.error('failed: ' + err);
        })
      console.log(4);
    },

回答by Tan Dat

If your goal is debugging WHAT included in ObserverVue instance, this is my solution:

如果您的目标是调试ObserverVue 实例中包含的内容,这是我的解决方案:

Print out that variable in templateblock belongs to your Component

打印出template块中的变量属于您的组件

After that, you can reformat the structure of the output to observe the detail.

之后,您可以重新格式化输出的结构以观察细节。

For example:

例如:

<template>
  <div>
    {{ pigeons }}
  <div>
</template>

Another way, if you wanna see it in console, you should put the console.loginto mountedphase. Because at createdphase, the this.pigeonsstill be empty. Ref: https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

另一种方式,如果你想在看到它console,你应该把console.log进入mounted阶段。因为在created相中,this.pigeons仍然是空的。参考:https: //vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

Hope this helpful.

希望这有帮助。

回答by Hasan Zarghami

The best way possible

最好的办法

obj2 = JSON.stringify(obj)
obj3 = JSON.parse(obj2)

It was brought by Evan You himself hereand more info

它被带到埃文你自己在这里和更多信息