在prop循环中观察父项并不更新
问题描述:
我有2个组件 - <my-component>
和<grand-child-comp>
。在prop循环中观察父项并不更新
在我的根目录中有一个多维对象,我的组件用prop来观察它。
<div id="app">
<my-component v-bind:account-types='accountTypes'>
</my-component>
</div>
在Vue调试器中,我可以看到my-component正在获取并正在监视accountTypes对象。但是,当试图在my-component's
模板中使用它时,它不起作用。
Vue.component('my-component', {
template: `
<div>
<grand-child-comp v-for="(account, index) in accountTypes" :key="index"></grand-child-comp>
</div>
`
}
最后,accountTypes物体看起来像:
{ 1 : [ 'a', 'b', 'c' ], 2: ['e', 'a', 'm'] }
答
的问题是,你正在做的v-for
,并在同一时间对同一元素传递的属性。您需要将它们嵌套,以便v-for
所在的元素包装<grand-child-comp>
。 The documentation recommends a template for this。
<template v-for="(account, index) in accountTypes">
<grand-child-comp :key="index"></grand-child-comp>
</template>
UPDATE:根据你在你的意见,说什么这听起来像你真正需要的是两个嵌套的for循环。
<!-- loop over account types -->
<div v-for="(accountId, values) in accountTypes">
<h3>{{ accountId }}</h3>
<!-- then loop over each individual value -->
<ul v-for="value in values">{{ value }}</ul>
</div>
您不需要使用组件。只有在您计划在应用程序周围的多个位置使用某些内容时才需要组件。仅仅因为for循环多次重复相同的元素并不意味着你实际上需要一个组件; for循环中的模板就足够了。
特别是你的小提琴,你正在'accountTypes'不正确地传递给'my-component'。 https://jsfiddle.net/50wL7mdz/51204/ – Bert
啊。我发现了这个问题。它与初始化根中的accountTypes有关。我正在使用'accountTypes:{}'。我试图把预定义的值,它的工作 – senty