Vuejs有条件的表演

时间:2018-01-26 16:33:13

标签: vue.js vuejs2 vue-component

我有很多部分针对不同的公司产品列表,我想在卡中添加其产品,只有我选择/点击的部分,但是它显示在页面中列出的所有公司,因为标记是相同的。下面是我的示例代码:`

<div ="app">
  <section>
    <h2>Company1 Products</h2>
    <p>
      <span class="available" v-on:click="select1 = !select1">Add item 1</span>
      <span class="available" v-on:click="select2 = !select2">Add item 2</span>
      <span class="available" v-on:click="select3 = !select3">Add item 3</span>
    </p>          
    <div class="product-selected">
      <p>Below product you have chosen</p>
      <div class="col-lg-6 col-12 show-products">
        <span v-if="select1">Item 1 Added</span>
        <span v-if="select2">Item 2 Added</span>
        <span v-if="select3">Item 3 Added</span>
      </div>
    </div>
  </section>
  <section>
    <h2>Company2 Products</h2>
    <p>
      <span class="available" v-on:click="select1 = !select1">Add item 1</span>
      <span class="available" v-on:click="select2 = !select2">Add item 2</span>
      <span class="available" v-on:click="select3 = !select3">Add item 3</span>
    </p>          
    <div class="product-selected">
      <p>Below product you have chosen</p>
      <div class="col-lg-6 col-12 show-products">
        <span v-if="select1">Item 1 Added</span>
        <span v-if="select2">Item 2 Added</span>
        <span v-if="select3">Item 3 Added</span>
      </div>
    </div>
  </section>
</div>
var vm = new Vue({
    el: '#app',
    data () {
      return {
        select1: false,
        select2: false,
        select3: false
      }
    }
});

`有forEach指令但不确定如何使用它。请帮忙!

1 个答案:

答案 0 :(得分:0)

您可以使用 v-for 为每个产品呈现一个部分。

然后,您可以为每个产品指定已选择项目的标志。

也许这样的事情可能会有所帮助:

<div="app">
  <section v-for="product in products">
    <h2>{{ product.name }}</h2>
    <p>
      <span class="available" v-on:click="product.select1 = !product.select1">Add item 1</span>
      <span class="available" v-on:click="product.select2 = !product.select2">Add item 2</span>
      <span class="available" v-on:click="product.select3 = !product.select3">Add item 3</span>
    </p>          
    <div class="product-selected">
      <p>Below product you have chosen</p>
      <div class="col-lg-6 col-12 show-products">
        <span v-if="product.select1">Item 1 Added</span>
        <span v-if="product.select2">Item 2 Added</span>
        <span v-if="product.select3">Item 3 Added</span>
      </div>
    </div>
  </section>
</div>

var vm = new Vue({
  el: '#app',
  data () {
    return {
      products: [
        {
          name: 'Company1 Products',
          select1: false,
          select2: false,
          select3: false
        },
        {
          name: 'Company2 Products',
          select1: false,
          select2: false,
          select3: false
        }
      ]
    }
  }
})