如何使用方法更改道具值 \- 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 的值?任何帮助将不胜感激

原文由 Harris Khan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 643
2 个回答

您可以将 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

原文由 Sukanta Bala 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

使用同步

在父组件中

<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");
  }
}

原文由 Jake Lam 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题