如何使用子值改变父值VUE JS



我需要更改父组件中Total的值。它将从子组件的值更改。

<!--Parent Component-->
<template>
<div class="section__wrapper">
<h1>Total:{{ this.total }}</h1>
<vItem title="First Item" price=2 @clicked="onClickChild"></vItem>
<vItem title="Second Item" price=3  @clicked="onClickChild"></vItem>
</div>
</template> 
<script>
import vItem from './v-item.vue';
export default {
data(){
return{
total:1000000,
}
},
components: {
vItem
}
}
</script>

<!--Child Component-->
<template>
<div class="item__body">
<div class="item__body__content">
<img src="" alt="" class="item__body__content__img">
<p>{{ this.totalOfItem }}</p>
<p class="item__body__content__title">{{ this.title }}</p>
<p class="item__body__content__price">{{ this.price }}</p>
<div class="item__body__content__control">
<button class="item__body__content__btn sell" @click="increasePrice">sell</button>
<input type="text" class="item__body__content__input" :value=this.count>
<button class="item__body__content__btn buy" @click="decreasePrice">buy</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
title: String,
price: Number,
},
data(){
return{
count:0,
totalOfItem: 0
}
},
methods:{
increasePrice(){
this.count -= 1
this.totalOfItem = this.count * this.price
},
decreasePrice(){
this.count += 1
this.totalOfItem = this.count * this.price
},
}
}
</script>

我需要一种方法,将总数减少为不同产品的数量。问题是,为单个产品编写这样的方法并不困难,但对于几个产品,这对我来说有点困难。每个项目都有价格和数量。

您必须使用vuejs emit: https://vuejs.org/guide/components/events.html.

在你的子组件上试试这样做:

export default {
props: {
title: String,
price: Number,
},
data(){
return{
count:0,
totalOfItem: 0
}
},
emits: ['onClickChild'],
setup(props, emit) {
function increasePrice(){
this.count -= 1
this.totalOfItem = this.count * this.price
emit('onClickChild', this.totalOfItem)
}
function decreasePrice(){
this.count += 1
this.totalOfItem = this.count * this.price
emit('onClickChild', this.totalOfItem)
}

return {
increasePrice,
decreasePrice,
}
}
}

相关内容

  • 没有找到相关文章

最新更新