繁体   English   中英

Laravel VueJS将动态数量绑定到产品列表组件中的每个输入

[英]Laravel VueJS bind dynamic quantity to each input in a products list component

尝试使用数据库中每个产品的列表创建动态表单。 该表格对每个产品都有以下字段:产品标题,产品价格,数量和总价。 我的问题是我不确定如何为每个产品数量输入添加v模型字段,因为该列表是从所有产品的v-for中提取的。 这是我的ProductsListForm vue组件模板的一部分:

<div v-for="product in products" :key="product.id" class="flex form-group">

  <div class="flex p-title">
    <label :for="product.title">{{ product.title }}</label>
    <small>{{ product.price }}$</small>
  </div>

  <div class="flex p-input">
    <input class="input" type="number" :name="product.title" v-model="quantity">
  </div>

  <div class="flex p-total">
    <span>Total: {{  product.price * quantity}}</span>
  </div>

</div>


export default {
  props: ['products'],
  data() {
      return {
          quantity: 0,
      }
  },
  methods: {}
}

所以我的问题是如何将数量绑定到每个单独的产品上? 现在,无论何时更新任何输入字段,它显然都将发生变化。任何帮助将不胜感激!

对于与产品(产品条目)相关的数量-您将必须将其传递给产品或将其本身排列成数组。

<div v-for="product in products" :key="product.id" class="flex form-group">

  <div class="flex p-title">
    <label :for="product.title">{{ product.title }}</label>
    <small>{{ product.price }}$</small>
  </div>

  <div class="flex p-input">
    <input class="input" type="number" placeholder="1" :name="product.title" v-model="quantity[product.id]">
  </div>

  <div class="flex p-total">
    <span>Total: {{  product.price * getProductQuantity(product) }}</span>
  </div>

</div>


export default {
  props: ['products'],
  data() {
      return {
          quantity: [],
      }
  },
  methods: {
    getProductQuantity(product) {
      return this.quantity[product.id] || 0;
    }
  }
}

而不是使用v-model ,您可以改为侦听每个元素上的input事件。

 new Vue({ el: '#app', data: () => ({ cart: [], products: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }, { id: 3, name: 'baz' } ] }), methods: { updateCart(event, product) { const index = this.cart.findIndex(i => i.name === product.name) const item = { name: product.name, quantity: event.target.value } if (index !== -1) { this.cart.splice(index, 1, item) } else { this.cart.push(item) } } } }) 
 ul, li { list-style: none; } #app { display: flex; flex-direction: row; justify-content: space-around; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <div> <h5>products</h5> <ul> <li v-for="product in products" :key="product.id"> <label>{{ product.name }}</label> <input @input="updateCart($event, product)" min="0" type="number"> </li> </ul> </div> <div> <h5>cart</h5> <ul v-if="cart.length"> <li v-for="item in cart" :key="item.id"> <p>{{ item.name }} {{ item.quantity }}</p> </li> </ul> <p v-else>no items in cart</p> </div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM