我有一个名为 cartComponent
的组件,其数据属性 cartCount
每当将新商品添加到购物车时该数据属性就会递增。
我需要使用该值来更新模板中不属于组件一部分的值。这可能吗?
这是我的父 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
}
});
最佳答案
这是使用 .sync
modifier 的理想情况.
来自文档:
<小时/>When a child component mutates a prop that has .sync, the value change will be reflected in the parent
根据您的情况,您可以添加 .sync
cCount
的修饰符模板中绑定(bind)的属性(假设您的组件具有 cCount
属性):
<cart :c-count.sync="cCount"></cart>
在购物车组件的脚本中发出 update:cCount
计数增加时发生的事件:
methods: {
incrementCount() {
this.cartCount++;
this.$emit('update:cCount', this.cartCount);
}
}
这将自动设置父 Vue 实例的值 cCount
属性设置为购物车组件的值 cartCount
属性。
此功能从 Vue 版本 2.3.0 开始可用,但如果您使用的是早期版本,这将为您提供相同的功能:
<cart :c-count="cCount" @update:foo="val => cCount = val"></cart>
这是因为<comp :foo.sync="bar"></comp>
只是语法糖:
<comp :foo="bar" @update:foo="val => bar = val"></comp>
关于javascript - 将值从组件传递到父实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45150634/