【问题标题】:Can't access sub-object in Vue JS 3无法访问 Vue JS 3 中的子对象
【发布时间】:2020-11-16 03:31:53
【问题描述】:

我是 VueJS 的新手,遇到以下问题:

我有一个模板,其中单击按钮会通过router.push 加载新模板,并且还会将 ID 作为数据发送。

模板:

<template>
    <div>
        {{ content.description }} // Works fine
        {{ content.subobject.logo }} // Logo not found
    </div>
</template>

在正在加载的新模板中,我具有以下用于将接收到的 ID 保存到数据中的功能:

    created: function() {
        this.ID = this.$route.params.data.toString()
    },

然后我在方法中有一个函数,它使用这个 ID 通过axios/get 获取数据:

    methods: {
        getContent: function() {
            axios.get("https://api-url.com/" + this.ID)
            .then((response) => {
                this.content = response.data.data
                console.log(response);
            }).catch(error => {
                console.log("ERRR:: ", error.response.data)
            });            
        }

    },

这个函数在mounted中被调用:

    mounted: function() {
        this.getContent()
    }

我的数据功能:

    data: function() {
    return {
       ID: '',
       content: [] as any
    }

API 返回的数据如下所示:

title: "this is the title"
description: "Lorem Ipsum"
subobject: {
   logo: "Logo URL"
}

当我在模板中使用 {{ content.title }}{{ content.description }} 时,它显示得很好。一旦我使用 {{ content.subobject.logo }} 我会得到一个错误“logo”未找到。

有趣的是,当我打开模板并在页面加载后添加{{ content.subobject.logo }} 时,保存它,然后热重新加载,它显示正常吗?!

似乎数据在首次加载时“不可用” - 但如果 {{ content.title }} 工作正常,那怎么可能?

非常感谢您的任何想法!

【问题讨论】:

  • 请分享您渲染该徽标的模板
  • @BoussadjraBrahim 没有什么特别的。用于测试其唯一的

标签: javascript vue.js vuejs3


【解决方案1】:

数据最初不可用,这意味着content 仍然没有内部字段值,以避免添加条件渲染,例如:

<div v-if="content.subobject">{{ content.subobject.logo }}</div>

你也可以这样做:

  data: function() {
    return {
       ID: '',
       content: null
    }
}
<template>
    <template v-if="content">
            <div >{{ content.subobject.logo }}</div>
            <div >{{ content.title }}</div>
    </template>

</template>

【讨论】:

  • 非常感谢,现在可以使用了!!一般问题:将每个元素包裹在“v-if”周围不是更好吗,只是为了确保它已经加载?
  • @sparks 既然您是 Vue 世界的新手,请尝试专注于 Vue 2,然后您就会熟悉它,您可以学习 vue 3 中引入的新概念
猜你喜欢
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 2022-01-14
  • 2023-04-11
相关资源
最近更新 更多