gpt4 book ai didi

javascript - 如何使用方法更改 props 值 - Vue.js

转载 作者:行者123 更新时间:2023-11-28 03:08:30 25 4
gpt4 key购买 nike

我对 vue 很陌生,正在处理一个基于 vue.js 的任务。我正在使用 Prop 在组件中显示我的数据。现在我想添加一个方法来增加产品的数量。

这是我的代码:

<div v-for="(products, index) in products">
<mdc-layout-cell span="2" align="middle">
{{ products.product_barcode }}
</mdc-layout-cell>
<mdc-layout-cell span="2" align="middle">
{{ products.product_quantity}}
</mdc-layout-cell>
<i class="mdc-icon-toggle material-icons float-left"
aria-pressed="false"
v-on:click="incrementItem(index)">
add
</div>

这是我的 JS:

export default {
props: [
'products',
],
methods: {

incrementItem(index) {
let item = this.products[index];
this.products[index].product_quantity =
this.products[index].product_quantity + 1;
console.log(this.products[index].product_quantity);
},
}

我可以在控制台中看到增加的值,但相应行中的值没有增加。我怎样才能增加product_quantity的值?任何帮助将非常感激

最佳答案

首先,就 vue 流程而言,记住永远不要直接改变 props。您应该改为更改父组件中的数据。为此,建议在子数据中创建 Prop 的副本,这样当单击按钮时,子数据会更改 -> 父数据会更改,这使得子 Prop 也会更改。有很多方法可以做到这一点。我没有你 parent 的组件代码,所以我在下面做了一个通用代码,你可以按照:

使用同步

在父组件中

<parent :products.sync=products />

在子组件方法中:

data() {
return {
productListInChildren: this.products; // pass props to children inner data
}
},
methods: {
incrementItem(index) {
//do modification in productListInChildren
let item = this.productListInChildren[index];
this.productListInChildren[index].product_quantity =
this.productListInChildren[index].product_quantity + 1;
// update it back to parents
this.$emit('update:products', this.productListInChildren)
}
}
<div v-for="(products, index) in productListInChildren"> // use productListInChildren instead
<mdc-layout-cell span="2" align="middle">
{{ products.product_barcode }}
</mdc-layout-cell>
<mdc-layout-cell span="2" align="middle">
{{ products.product_quantity}}
</mdc-layout-cell>
<i class="mdc-icon-toggle material-icons float-left"
aria-pressed="false"
v-on:click="incrementItem(index)">
add </i>
</div>

第二:在代码设计方面,建议在您的情况下,子级应该只处理显示逻辑(dumb组件)。更改数据的逻辑应该移至父级(如 Controller )。如果是这样的话。您可以在父组件中创建一个方法并添加增量逻辑:

父组件

<parent :products=products @increment="incrementInParent"/>



methods: {
incrementInParent() {// move the logic here}
}

子组件

methods: {
incrementItem(index) {
// call the methods in parents
this.$emit("increment");
}
}

关于javascript - 如何使用方法更改 props 值 - Vue.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60371970/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com