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

Har*_*han 3 javascript vue.js vue-component

我对 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>
Run Code Online (Sandbox Code Playgroud)

这是我的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);
      },
    }
Run Code Online (Sandbox Code Playgroud)

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

Ngo*_*Lam 5

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

使用同步

在父组件中

<parent :products.sync=products />
Run Code Online (Sandbox Code Playgroud)

在儿童组件方法中:

<parent :products.sync=products />
Run Code Online (Sandbox Code Playgroud)
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)
  }
}
Run Code Online (Sandbox Code Playgroud)

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

父母组件

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



methods: {
incrementInParent() {// move the logic here}
}
Run Code Online (Sandbox Code Playgroud)

儿童组件

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