[英]Pass value from a component to the parent instance
I have a component named cartComponent
with a data property cartCount
that gets incremented whenever a new item is added to the cart.我有一个名为
cartComponent
的组件,它的数据属性cartCount
会在每次将新商品添加到购物车时递增。
I need to use that value to update the value in the template which is not a part of the component.我需要使用该值来更新模板中不属于组件的值。 Is this possible?
这可能吗?
Here's is the script for my parent Vue instance:这是我的父 Vue 实例的脚本:
new Vue({
el: "#cart-app",
components: {
cart: cartComponent
},
data: {
searchQuery: '',
appliedFilters: ['Day 1'],
purchaseData: json,
cCount: 0 // CARTCOUNT; NEEDS TO BE UPDATED FROM COMPONENT
}
});
This is the ideal case for using the .sync
modifier .这是使用
.sync
修饰符的理想情况。
From the documentation:从文档中:
When a child component mutates a prop that has .sync, the value change will be reflected in the parent
当子组件改变具有 .sync 的 prop 时,值更改将反映在父组件中
In your case, you could add the .sync
modifier to the cCount
property being bound in the template (assuming that your component has a cCount
property):在您的情况下,您可以将
.sync
修饰符添加到模板中绑定的cCount
属性(假设您的组件具有cCount
属性):
<cart :c-count.sync="cCount"></cart>
And in the script for the cart component emit an update:cCount
event when the count is incremented:并且在购物车组件的脚本中,当计数增加时会发出一个
update:cCount
事件:
methods: {
incrementCount() {
this.cartCount++;
this.$emit('update:cCount', this.cartCount);
}
}
This will automatically set the value of the parent Vue instance's cCount
property to the value of the cart component's cartCount
property.这会自动将父 Vue 实例的
cCount
属性的值设置为购物车组件的cartCount
属性的值。
Here's a working fiddle.这是一个工作小提琴。
This feature is available starting in Vue version 2.3.0, but if you are using an earlier version, this would give you the same functionality:此功能从 Vue 版本 2.3.0 开始可用,但如果您使用的是早期版本,这将为您提供相同的功能:
<cart :c-count="cCount" @update:foo="val => cCount = val"></cart>
This is because <comp :foo.sync="bar"></comp>
is just syntactic sugar for:这是因为
<comp :foo.sync="bar"></comp>
只是语法糖:
<comp :foo="bar" @update:foo="val => bar = val"></comp>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.