我在vue中是相当陌生的,正在从事基于vue.js的任务。我正在使用道具在组件中显示数据。现在,我想添加一种增加产品数量的方法。
这是我的代码:
<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中的对象和数组警告,视图不会对这些更改做出反应。您可以在这里阅读
https://vuejs.org/v2/guide/reactivity.html
您可以使用$set
使模板对Object和Array中的更改做出反应。这是我的沙盒URL,可以回答您的问题
首先,在Vue流程方面,切记永远不要直接改变道具。您应该改为修改父组件中的数据。为此,建议在子数据中创建道具副本,以便在单击按钮时,子数据会更改->父数据,这会使子道具也发生变化。有很多方法可以做到这一点。我没有父母组件代码,因此我在下面做了一个通用代码,您可以按照以下步骤进行:
使用同步
在父母部分中
<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>
[第二:就代码设计而言,建议您的情况下,子代仅应处理显示逻辑(哑组件)]。更改数据的逻辑应移交给父母(如控制器)。如果是这样的话。您可以在父组件中创建一个方法并添加增量逻辑:
父母组件
<parent :products=products @increment="incrementInParent"/>
methods: {
incrementInParent() {// move the logic here}
}
儿童组件
methods: {
incrementItem(index) {
// call the methods in parents
this.$emit("increment");
}
}
您可以将props
值分配给变量。然后使用它的子组件。
export default {
props: {
products: Array,
},
data(){
return {
newProducts: this.products,
}
}
}
您应在子组件中更改props
结构。在子组件中使用newProducts
,并且如果您更新父道具数据,则应在子与父之间的通信中使用emit
。
有关进一步的亲子沟通,您可以按照以下教程进行:https://www.bdtunnel.com/2018/02/vue-js-component-communication-complete.html