首页 > 解决方案 > 单击循环后如何更改颜色?

问题描述

我有如下循环:

data: {
  show: false
}
.test {
  hight: 10px;
  background-color: red;
}

.test2 {
  hight: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div v-for="value in data" :key="value.id">
  <div class="test" v-bind:class="{ test2: show }" v-on:click="show = !show">
  </div>
</div>

现在,如果我单击 any div,它将所有 div 的高度从 15 更改为 10 或从 10 更改为 15。

但是,我想更改div我点击的唯一一个。我怎样才能做到这一点?

标签: javascriptloopsvue.jsbind

解决方案


您需要show为每个元素添加变量:

new Vue({
  el: "#app",
  data: {
  	show: [],
    items: []
  },
  created() {
    fakeFetch().then((items) => {
       this.items = items;
       this.show = this.items.map(() => false);
    });
  },
  methods: {
  	isShown(i) {
    	return this.show[i]
    },
    changeShow(i) {
    	Vue.set(this.show, i, !this.show[i]);
    }
  }
})

function fakeFetch() {
  return new Promise((resolve, reject) => {
     let count = Math.floor(Math.random() * 20) + 1;
     let result = [];
     for (let i = 0; i < count; i++) {
       result.push({ text: Math.random() });
     }
     resolve(result);
  })
}
.test {
  height:10px;
  background-color: red;
  margin: 10px;
}
.test2 {
  height: 35px;
 }
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="app">
  <h2>Items:</h2>
  <div 
  class="test" 
  :class="{ test2: isShown(index) }"
  @click="changeShow(index)" 
  v-for="(item,index) in items" :key="index">
  </div>
</div>

PS为了避免这种使用show数组的例程,您可以将每个元素定义为组件并使用单个变量在其中切换可见性show


推荐阅读