[英]how to change props value using method - Vue.js
我是 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 的值? 任何帮助都将不胜感激
您可以将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
首先,在 vue 流程方面,切记不要直接改变 props 。 您应该改变父组件中的数据。 为此,建议在 children 数据中创建 props 的副本,因此当单击按钮时,children 数据更改 -> parents 数据更改,这使得 children 道具也发生变化。 有很多方法可以做到这一点。 我没有你父母的组件代码,所以我在下面制作了一个通用代码,你可以遵循:
使用同步
在父组件中
<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。 您应该使用事件通信模式进行子和父通信。 在更改数组中的特定值(尤其是数组中的特定索引)或更新对象中的属性时,由于 Vue 中的对象和数组警告,视图不会对这些更改做出反应。 你可以在这里阅读它
https://v2.vuejs.org/v2/guide/reactivity.html
您可以使用$set
使模板对 Object 和 Array 中的更改做出反应。 这是我的沙盒网址,可以回答您的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.