v-for中的Vue.js切换类

时间:2018-08-07 10:31:24

标签: class dynamic vue.js toggle v-for

我正在用v-for循环列出项目。我有一些来自服务器的API数据。

items: [
   {
       foo: 'something',
       number: 1
   },
   {
       foo: 'anything',
       number: 2
   }
]

我的模板是:

<div v-for(item,index) in items @click=toggleActive>
     {{ item.foo }} 
     {{ item.number }} 
</div>

JS:

methods: {
    toggleActive() {
        //
    }
}

我如何使用:class = {active:something}切换活动类? 附言:我的商品没有布尔值

4 个答案:

答案 0 :(得分:3)

您可以尝试实现以下内容:

<div 
  v-for="(item, index) in items"
  v-bind:key="item.id" // or alternativelly use `index`.
  v-bind:class={'active': activeItem[item.id]}
  @click="toggleActive(item)"
>

JS:

data: () => ({ 
  activeItem: {}, 
}),

methods: {
  toggleActive(item) {
    if (this.activeItem[item.id]) {
      this.removeActiveItem(item);

      return;
    }

    this.addActiveItem(item);
  },
  addActiveItem(item) {
    this.activeItem = Object.assign({},
      this.activeItem,
      [item.id]: item,
    );
  },
  removeActiveItem(item) {
    delete this.activeItem[item.id];
    this.activeItem = Object.assign({}, this.activeItem);
  },
}

答案 1 :(得分:0)

我遇到了同样的问题,尽管要找到大量有用的信息并不容易,但实现起来却相对容易。我有一个商店列表,这些商店映射到一种可单击按钮的标签云。单击其中之一时,“添加的”类将添加到链接。标记:

<div class="col-sm-10">
    <a href="#" class="tagCloud" v-for="store in stores" v-on:click="toggleAdd(store)" v-bind:class="{ 'added': selectedStoreIds.indexOf(store.id) !== -1 }">{{ store.name }}</a>
</div>

以及相关的脚本(在这种情况下为TypeScript)。 toggleAddselectedStoreIds添加或删除商店ID,该类将自动更新:

new Vue({
    el: "#productPage",
    data: {
        stores: [] as StoreModel[],
        selectedStoreIds: [] as string[],
    },
    methods: {
        toggleAdd(store: StoreModel) {
            let idx = this.selectedStoreIds.indexOf(store.id);
            if (idx !== -1) {
                this.selectedStoreIds.splice(idx, 1);
            } else {
                this.selectedStoreIds.push(store.id);
            }
    },
    async mounted () {
        this.stores = await this.getStores(); // ajax request to retrieve stores from server
    }
});

Marlon Barcarol's answer为我解决了很多问题。

答案 2 :(得分:0)

可以分两个步骤完成。

1)在父组件中创建v-for循环,例如

<myComponent v-for="item in itemsList"/>

data() {
  return {
    itemsList: ['itemOne', 'itemTwo', 'itemThree']
  }
}

2)使用所有必要的逻辑创建子myComponent本身

<div :class="someClass" @click="toggleClass"></div>

data(){
  return {
    someClass: "classOne"
  }
},
methods: {
  toggleClass() {
    this.someClass = "classTwo";
  }
}

这样,v-for循环中的所有元素都将具有独立的逻辑,而与同级元素无关

答案 3 :(得分:0)

我正在从事一个项目,但我有相同的要求,这是代码:

您可以忽略CSS并选择vue逻辑:)

new Vue({
  el: '#app',
  data: {
    items: [{ title: 'Finance', isActive: false }, { title: 'Advertisement', isActive: false }, { title: 'Marketing', isActive: false }],
  },
})
body{background:#161616}.p-wrap{color:#bdbdbd;width:320px;background:#161616;min-height:500px;border:1px solid #ccc;padding:15px}.angle-down svg{width:20px;height:20px}.p-card.is-open .angle-down svg{transform:rotate(180deg)}.c-card,.p-card{background:#2f2f2f;padding:10px;border-bottom:1px solid #666}.c-card{height:90px}.c-card:first-child,.p-card:first-child{border-radius:8px 8px 0 0}.c-card:first-child{margin-top:10px}.c-card:last-child,.p-card:last-child{border-radius:0 0 8px 8px;border-bottom:none}.p-title .avatar{background-color:#8d6e92;width:40px;height:40px;border-radius:50%}.p-card.is-open .p-title .avatar{width:20px;height:20px}.p-card.is-open{padding:20px 0;background-color:transparent}.p-card.is-open:first-child{padding:10px 0 20px}.p-card.is-open:last-child{padding:20px 0 0}.p-body{display:none}.p-card.is-open .p-body{display:block}.sec-title{font-size:12px;margin-bottom:10px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<div id="app" class="p-5">
  <div class="p-wrap mx-auto">
    <div class="sec-title">NEED TO ADD SECTION TITLE HERE</div>
    <div>
      <div v-for="(item, index) in items" v-bind:key="index" class="p-card" v-bind:class="{'is-open': item.isActive}"
        v-on:click="item.isActive = !item.isActive">
        <div class="row p-title align-items-center">
          <div class="col-auto">
            <div class="avatar"></div>
          </div>
          <div class="col pl-0">
            <div class="title">{{item.title}}</div>
          </div>
          <div class="col-auto">
            <div class="angle-down">
              <svg aria-hidden="true" focusable="false" data-prefix="far" data-icon="angle-down" role="img"
                xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"
                class="svg-inline--fa fa-angle-down fa-w-10 fa-3x">
                <path fill="currentColor"
                  d="M151.5 347.8L3.5 201c-4.7-4.7-4.7-12.3 0-17l19.8-19.8c4.7-4.7 12.3-4.7 17 0L160 282.7l119.7-118.5c4.7-4.7 12.3-4.7 17 0l19.8 19.8c4.7 4.7 4.7 12.3 0 17l-148 146.8c-4.7 4.7-12.3 4.7-17 0z"
                  class=""></path>
              </svg>
            </div>
          </div>
        </div>
        <div class="p-body">
          <div class="c-card"></div>
          <div class="c-card"></div>
          <div class="c-card"></div>
        </div>
      </div>
    </div>
  </div>
</div>