如何在v-for内部发生更改时更新父级的数据对象。我有一个在父组件中使用的子组件。
ParentComponent.vue
<template>
....
....
<child-component
v-for="i in count"
ref="childComponent"
:key="i"
currentPage="i" // currentPage doesn't update.
:page="i"
/>
<q-header>
{{currentPage}} // always displays default value:1
</q-header>
</template>
<script>
data () {
return {
pageCount: 10,
currentPage: 1,
}
},
每当我在v-for内部更改时,我如何更新数据对象的currentPage。我试过用手表,但运气不好。我无法访问子组件,也无法修改它。
非常感谢!
此处对v-for
在child-component
上的工作方式有一些轻微的混淆。将currentPage="i"
写入属性(实际上应该是v-bind:currentPage
,以便将i
解释为JS(将简单地声明每个child-component
上的属性
每当我在v-for 内部更改时,我如何更新数据对象的currentPage
CCD_;改变";在常规JavaScript应用程序内部运行for循环的传统上下文中。在Vue中,渲染逻辑和应用程序的逻辑是分开的,这是正确的,因为作为渲染的一部分运行逻辑实际上没有意义。
例如,让我们看看您的应用程序将如何呈现child-component
:
<!-- Vue output -->
<child-component ... currentPage="1" />
<child-component ... currentPage="2" />
<child-component ... currentPage="3" />
因此,让我们来看看将渲染逻辑与应用程序的逻辑分离。
我意识到你无法访问child-component
,但根据上下文,我认为它是某种选项卡功能(基于你试图为"当前页面"设置一个值——请更具体地说,我可以更新我的答案(。
我们需要弥合呈现逻辑和应用程序逻辑之间的差距,我们可以通过使用事件来做到这一点:
<child-component
v-for="i in count"
:ref="`childComponent-${i}`" // ref should be unique so add the i as part of it
:key="i"
:page="i"
v-on:click="currentPage = i" // when the user clicks this child component, the current page will be updated
/>
你可能需要利用click
之外的其他活动,但我希望这能让你更接近你想要实现的目标。要更新currentPage
的值,必须有某种用户输入,所以只需找出哪个事件最有意义。也许您正在使用的child-component
库具有更合适的自定义事件。
您应该研究自定义事件。
https://v2.vuejs.org/v2/guide/components-custom-events.html
想法是,只要子组件中有您的愿望的更新,您就可以执行this.$emit(“change”)
,它将抛出一个事件。
在父级,您可以通过@change=“myMethod”
捕获此事件作为属性之一。
methods: {
myMethod() {
console.log("Testing")
}
}
<child-component
v-for="i in count"
ref="childComponent"
:key="i"
currentPage="i"
:page="i"
@change=“myMethod”
/>
如果有帮助,请告诉我。