I'm studying vue js3 - I ran into a misunderstanding of linking variables in components. You need to pass the @click event from the child component, so that the value in the parent has changed. Example:
children component
<div id="btn" @click="addToCart(item)"> Add to cart</div>
Parent component
<p >{{cardValue}}</p>
It is necessary to increase the value of {{cardValue}} by 1 when clicking in the child component
CodePudding user response:
As per my understanding, You are working on an e-commerce application where you want to add the items in a cart from a child component but cart items counter is in parent component. If Yes, Then it is necessary to emit
an event to parent on click of Add to cart
button, So that it will increment the counter by 1
.
Live Demo :
const { createApp, ref, defineComponent } = Vue;
const app = createApp({
setup() {
const cartItemsCount = ref(0)
// expose to template and other options API hooks
return {
cartItemsCount
}
}
});
app.component('item', defineComponent({
template: '<button @click="addToCart">Add to Cart</button>',
methods: {
addToCart() {
this.$emit("addToCart");
}
}
}));
app.mount('#app')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="app">
<div>
Items added into the cart : {{ cartItemsCount }}
</div>
<item @add-to-cart="cartItemsCount = 1"></item>
</div>