【问题标题】:Why does my API data show up as undefined when using a v-if in vue.js?为什么在 vue.js 中使用 v-if 时我的 API 数据显示为未定义?
【发布时间】:2021-06-17 11:36:23
【问题描述】:

模板

<template>
<div class="profile-container">
    <div class="theme-container">
      <img class="theme" src="#" alt="PH">
    </div>
    <div class="profile-pic-container">
      <img class="profile-pic" :src="responseData.profile_pic" alt="PH">
    </div>
    <div class="profile-info-container">
      <div class="follow-message-button-container">
        <button class="direct-message-button btn"><svg><use href="#chat-icon"></use></svg></button>
        <Follow v-if="responseData.followers.includes($store.state.userId)"></Follow>
      </div>
      <h3 class="profile-username">@{{responseData.username}}</h3>
      <p class="profile-bio">{{responseData.bio}}</p>
      <div class="follower-following-count">
        <a href="#" class="follower-count">Followers: {{responseData.followers.length}}</a>
        <a href="#" class="following-count">Following: {{responseData.following.length}}</a>
      </div>
    </div>
  </div>
</template>

responseData.followers.length 可以正常工作,但responseData.followers.includes($store.state.userId) 不能。它给了我一个错误说:

无法读取未定义的属性包括

脚本

<script>
import Follow from "@/components/Follow";
import getAPICall from "@/mixins/getAPICall";
import getSecondAPICall from "@/mixins/getSecondAPICall";
import Post from "@/components/Post";

export default {
  name: "Profile",
  components: {Post, Follow},
  data() {
    return {
      list: [],
      responseData: {},
      responseData2: {},
      APIUrl: `api/user/${this.$route.params.userId}`
    }
  },
  methods: {
  },
  mixins: [getAPICall, getSecondAPICall],
  created() {
    this.getAPICall(this.APIUrl)
    this.getSecondAPICall(`api/user-post-list/${this.$route.params.userId}`)
  }
}
</script>

这就是我的 axios api 调用的样子

混音

import {getAPI} from "@/axios.api";
import store from "@/store";

export default {
    data() {
        return {
            getAPICall(APIUrl) {
                getAPI.get(APIUrl, {headers: {Authorization: `Bearer ${this.$store.state.accessToken}`}}
                ).then(response => {
                    this.responseData = response.data
                }).catch(err => {
                    console.log(err)
                    store.dispatch('useRefreshToken'
                    ).then(_ => {
                        console.log(_)
                        getAPI.get(APIUrl, {headers: {Authorization: `Bearer ${this.$store.state.accessToken}`}}
                        ).then(response => {
                            this.responseData = response.data
                            }).catch(err => {
                                console.log(err)
                            })
                    }).catch(err => {
                        console.log(err)
                    })
                    }
                )
            }
        }
    }
}

当我在 created() 挂钩中控制台记录 responseData 时,我得到一个空代理。

当我在挂载的钩子中进行控制台登录时,我会得到一个具有正确数据的代理对象,但是如果我尝试从挂载的钩子中调用我的 API 混合,我仍然会遇到与以前相同的错误,并且我的其余页面会中断。

浏览器中的控制台记录 responseData 返回 undefined。

【问题讨论】:

    标签: javascript vue.js axios


    【解决方案1】:

    尝试确保您拥有 responseData 。由于 vue 第一次创建模板,它正在寻找 reponseData 中的属性。在这种情况下,它没有找到属性。我遇到过几次这样的问题。页面在 api 返回数据之前呈现。声明responseData: null并检查

    <div class="profile-container" v-if=" responseData !== null">
    

    【讨论】:

      【解决方案2】:

      问题来了,

      responseData.followers 在渲染时不会立即发生。因为api调用响应需要时间。所以像这样替换那行

        <Follow 
          v-if="responseData.followers && responseData.followers.includes($store.state.userId)">
          </Follow>
      

      您可能应该同步调用这些 api,但这取决于您的要求。如果这两个 api 之间有任何依赖关系,那么应该同步调用,但任何其他情况都可以。

      //asynchronous operation
      
          created() {
              this.getAPICall(this.APIUrl)
              this.getSecondAPICall(`api/user-post-list/${this.$route.params.userId}`)
            }
      
      //synchronous operation
      async created() {
         await this.getAPICall(this.APIUrl)
         await this.getSecondAPICall(`api/user-post-list/${this.$route.params.userId}`)
        }
      

      【讨论】:

        【解决方案3】:

        您的代码几乎不需要更改,例如 followers: [] 已在您的 data() 返回中设置

        data() {
            return {
              list: [],
              responseData: {followers: []},
              responseData2: {},
              APIUrl: `api/user/${this.$route.params.userId}`
            }
          },
        

        【讨论】:

          猜你喜欢
          • 2021-11-18
          • 2020-11-29
          • 2021-01-16
          • 2016-11-16
          • 2019-11-07
          • 1970-01-01
          • 2020-04-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多