【问题标题】:Toggle button text on a loop VUE在循环 VUE 上切换按钮文本
【发布时间】:2020-11-19 20:31:39
【问题描述】:

我有一个产品循环,每个产品都有一张产品卡。 当从Add to cart点击到Remove from cart时,我希望能够切换按钮。

问题是所有产品按钮同时切换,我不希望只切换单个产品卡按钮来引用每个单独的产品。

在我的 HTML 中

      <div v-for="product of products" :key="product.id">
         <span class="btn btn-primary mt-5 modal-toggle-btn"  @click="addGift(product, text, 'index')" v-show="!isAdded">Añadir a la box</span>
         <span class="btn btn-primary mt-5 modal-toggle-btn" @click="removeGift(product, 'index')" v-show="isAdded">Quitar de la box</span>
      </div>

Vue 数据

isAdded: false

我的 Vue 方法

  addGift(product, index){
     this.campaign.selectedproducts.push({name: product.name });
     this.isAdded = true
  },
  removeGift(product, index){
     this. campaign.selectedproducts.splice(index, 1)
     this.isAdded = false
  },

【问题讨论】:

  • 你正在寻找类似我的回答 here
  • 您好,我尝试将索引放入参数中,但我不知道如何以正确的方式使用该方法(更新答案)。谢谢!
  • 文字是什么意思?它是数据属性吗?
  • 抱歉,仅供测试,已解决问题

标签: vue.js


【解决方案1】:

我的建议是:

  1. 将产品按钮划分为一个单独的组件。

  2. 使用addedIds 作为数组来存储添加的产品ID,而不是isAdded 布尔值。

  3. 使用Vue event handling 传达父子点击事件。

  4. 将点击的产品id 存储到点击事件中的addedProductId。

  5. 检查 addedProductId 以确保添加了产品或 不在子组件中。

示例:

ProductButtons.vue(子组件)

<template>
  <div>
    <span class="btn btn-primary mt-5 modal-toggle-btn"  @click="addGift" v-show="!isAdded">Añadir a la box</span>
    <span class="btn btn-primary mt-5 modal-toggle-btn" @click="removeGift" v-show="isAdded">Quitar de la box</span>
  </div>
</template>

<script>
export default {
  name: "ProductButtons",
  props: {
    product: { type: Object, required: true },
    addedIds: { type: Array, required: true },
  },
  computed: {
    isAdded() {
      return this.addedIds.indexOf(this.product.id) > -1;
    },
  },
  methods: {
    addGift(){
      this.$emit('addGift', this.product);
    },
    removeGift(product){
      this.$emit('addGift', this.product);
    },
  }
}
</script>

在您的 HTML 中

<template v-for="product of products" :key="product.id">
    <product-buttons :product="product" :addedIds="addedIds" @addGift="addGift" @removeGift="removeGift"></product-buttons>
</template>

Vue 数据

addedIds: []

你的 Vue 方法

  addGift(product){
     this.campaign.selectedproducts.push({name: product.name });
     // save product id as an added id
     const index = this.addedIds.indexOf(product.id);
     if (index === -1) {
         this.addedIds.push(product.id);
     }
  },
  removeGift(product){
     this.campaign.selectedproducts.splice(index, 1);
     // remove product id
     const index = this.addedIds.indexOf(product.id);
     if (index > -1) {
         this.addedIds.splice(index, 1);
     }
  },

【讨论】:

  • 非常感谢 Zugor,我正在尝试在我的 Rails 应用程序中实现这一点
  • 不客气。如果答案对您来说是正确的,您可能会接受。
猜你喜欢
  • 2018-07-23
  • 1970-01-01
  • 2020-01-05
  • 2019-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 2019-03-18
相关资源
最近更新 更多