【问题标题】:Strange issue with Vue2 child component object v-for list renderVue2子组件对象v-for列表渲染的奇怪问题
【发布时间】:2018-04-21 12:38:33
【问题描述】:

我有一个包含数组和对象的父组件:

    data() {
        return {
            products: [],
            attributes: {},
        }
    },

加载我的父组件时,它会获取一些 AJAX 数据并填充变量:

    mounted() {
        axios.get('/requests/getProducts/' + this.currentCategory).then(response => {
            this.products = response.data;
            this.createAttributes(); // runs some methods to populate the attributes object
        });
    }, 

然后,我将使用一个子组件来显示属性。来自父模板的代码:

    <search-attributes :attributes="attributes"></search-attributes>

我的子组件中声明了道具:

    props: ['attributes'],

到目前为止一切顺利,我可以控制台记录来自父母和孩子的数据...

问题是当我尝试v-for 子组件中的属性时,它根本不返回任何内容:

/////////////// this does not render anything ///////////////

<template>
    <div>
        <div v-for="(value, key) in attributes">
            {{ key }}
        </div>
    </div>
</template>

但是,如果我将产品和属性变量都传递给子组件,并在子组件中渲染产品,属性将开始工作!

/////////////// this works /////////////
<template>
    <div>
        <div v-for="(value, key) in attributes">
            {{ key }}
        </div>
    {{ products }}
    </div>
</template>

这到底是怎么回事?

您需要查看我的父方法吗?

【问题讨论】:

  • 尝试制作属性计算属性并将其支撑给孩子们?
  • 你能把attributes转储到你的模板中看看发生了什么

标签: vue.js vuejs2 vue-component


【解决方案1】:

我希望您遇到change detection caveat。当您向对象动态添加属性时,Vue 无法检测到。在这种情况下,您从一个空的 attributes 对象开始。如果你在不使用 $set 的情况下向它添加属性,那么 Vue 不会理解发生了变化并且不会更新 DOM。

更新createAttributes 以使用$set

当你传递 products 时它起作用的原因是 Vue 可以检测到你所做的更改 (this.products = response.data),所以它呈现 DOM,它显示最新的 attributes 为产品。

【讨论】:

  • 感谢您的回答 - 现场。我花了一段时间才弄清楚如何让它与 $set 一起工作,但现在一切都很好。感谢您的快速响应!
  • 实际上,我以为我的 $set 工作正常,但事实证明它没有正确收集数据,现在我又回到了原点。我在这里创建了一个关于它的新线程:stackoverflow.com/questions/47190211/…
猜你喜欢
  • 2014-02-15
  • 2014-02-20
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 2021-08-19
  • 2021-08-16
  • 2011-07-30
相关资源
最近更新 更多