未定义的变量 - 虽然 api 获取 |公理道具

Undefined variable - While api fetch | Axios | Props

我的主要组成部分 - 主页

一个非常简单的组件,我将 fetch 变量传递给另一个组件。

<template>
      <Page actionBarHidden="true">
        <ComponentA :api="api.somevariable"></ComponentA>
      </Page>
    </template>

    <script>
    import axios from "axios";
    import ComponentA from "./ComponentA.vue";
    export default {
      data() {
        return {
          isLoading: false,
          result: []
        };
      },
       components: {
        ComponentA,
      },
       created() {
        this.loadData();
      },
       methods: {
           async loadData() {
              let self = this;

              console.log("fetch");

              self.isLoading = true;
              const { data } = await Endpoints.get();
              self.isLoading = false;
              self.api = data;
              console.log(data); // returns the data as intended
            }
       }
    </script>

组件A也很简单

<template>
  <Label :text="somevariable"></Label>
</template>
<script>
export default {
  data() {
    return {
      somevariable: 0
    };
  },
  props: {
    api: {
      type: Number,
      required: true
    }
  },
  mounted() {
     this.somevariable = this.api;
  }
};
</script>

我得到的错误是 [Vue warn]: Invalid prop: type check failed for prop "api"。值为 NaN 的预期数字,在 componentA 中得到未定义,在对 console.logs 进行一些引用和重新引用之后,它实际上获取了该值。我不确定为什么会这样,我的方法错了吗?这让我很沮丧,已经好几个小时都弄不明白了。

api 未在第一个组件的 data 中定义,因此它不会响应。那应该会在控制台中给您一条警告消息。

data () {
  return {
    api: null,
    isLoading: false,
    result: []
  };
}

第二个问题是,当组件首次呈现时,它还没有从服务器加载 api。使用 await 对此无济于事,呈现模板将在异步请求完成之前发生。

考虑到 componentA 当前的编写方式,它将无法处理 api 在首次创建时丢失的情况。因此,您需要使用 v-if 来推迟创建,直到该数据可用:

<ComponentA v-if="api" :api="api.somevariable"></ComponentA>

如果没有 v-if 检查,它只会传递 api 的初始值,这在您的原始代码中是 undefined。这就是导致问题中提到的警告的原因。

当您谈论 'quoting and requoting of console.logs' 时,我会假设这些更改只是触发热重载,这很容易导致组件使用新数据重新渲染.否则不会发生这种情况,因为 api 未包含在原始 data.

中导致缺乏反应性