Vue - 循环遍历一组对象,并在单击时突出显示所选项目

时间:2018-05-24 16:17:11

标签: javascript arrays object vue.js vuejs2

我有一个包含数据的对象数组,我使用map输出到DOM。列表中的每个项目都有一个@click事件监听器。当您单击其中一个项目时,我希望通过添加css类来突出显示它,例如'hover'。所以基本上它应该像菜单系统一样工作。单击某个项目时,该项目将突出显示,而其他项目不应突出显示,反之亦然。

我现在设置它的方式,列表中的所有项目都会突出显示,这不是我想要做的逻辑。我使用了console.log来显示已单击的项目。但是,我仍然没有弄明白,如何制作所选项目,突出显示而不是整个列表?

<template>
<div>
    <div>
        <h1>Dragonball</h1>
    </div>
    <div>
        <ul>
            <li v-for="(dragonBallFighters, index) of dragonBallFighter" @click="toggleClass(dragonBallFighters.id)" :key=dragonBallFighters.id :class="{hover: active}">
                <div class="dragonball-container">
                    <div class="dragonball-stats">
                    <h1>{{index}}, {{dragonBallFighters.name}}</h1>
                    <p>{{dragonBallFighters.race}}</p>
                    <p>{{dragonBallFighters.specialAttack}}</p>
                </div>
                <div class="dragonball-image">
                    <img :src="dragonBallFighters.img" :alt="dragonBallFighters.name" />
                </div>
                </div>
            </li>
        </ul>
    </div>
</div>
</template>

<script>
export default {
  data() {
    return {
      active: false,
      dragonBallFighter: [
        {
          id: 1,
          name: 'Goku',
          race: 'Sayain',
          specialAttack: 'Kamehameha Wave',
          img:
            'https://geeksnipper.com/wp-content/uploads/2018/03/Screen-Shot-2018-03-04-at-8.52.28-AM.png'
        },
        {
          id: 2,
          name: 'Vegeta',
          race: 'Sayain',
          specialAttack: 'Final Flash',
          img:
            'https://nerdreactor.com/wp-content/uploads/2018/01/vegeta-ssb.jpg'
        },
        {
          id: 3,
          name: 'Brolly',
          race: 'Sayain',
          specialAttack: 'Crusher Blast',
          img: 'http://media.comicbook.com/2017/05/broly-995283-1280x0.png'
        },
        {
          id: 4,
          name: 'Majin Buu',
          race: 'Unknown',
          specialAttack: 'Absorbtion',
          img: 'https://i.ytimg.com/vi/50GF26RBWjw/maxresdefault.jpg'
        },
        {
          id: 5,
          name: 'Janemba',
          race: 'Unknown',
          specialAttack: 'Teleportation Warp',
          img:
            'https://vignette.wikia.nocookie.net/villainstournament/images/f/f1/Super_janemba.png/revision/latest?cb=20140311163545'
        },
        {
          id: 6,
          name: 'Tien',
          race: 'Human',
          specialAttack: 'Tri Beam',
          img:
            'http://i1.wp.com/www.dragonball.co/wp-content/uploads/2016/08/tien_banner.png?fit=704%2C396'
        },
        {
          id: 7,
          name: 'Vegito SSJB',
          race: 'Sayian',
          specialAttack: 'Final kamehameha',
          img:
            'http://i1.wp.com/shoryuken.com/wp-content/uploads/2018/05/Vegito-Blue-SSGSS-Attack.png?fit=750%2C400&resize=750%2C400'
        },
        {
          id: 8,
          name: 'Toppo',
          race: 'Unknown',
          specialAttack: 'Finger Blasters',
          img: 'https://i.ytimg.com/vi/_Lz9bTEL1dM/maxresdefault.jpg'
        },
        {
          id: 9,
          name: 'Dyspo',
          race: 'Unknown',
          specialAttack: 'Super Hyper Lightspeed Mode',
          img:
            'https://pre00.deviantart.net/5458/th/pre/f/2017/148/1/8/dragon_ball_super_dyspo_by_giuseppedirosso-dbaqm0s.jpg'
        },
        {
          id: 10,
          name: 'Future Trunks',
          race: 'Human',
          specialAttack: 'Galick Gun',
          img:
            'https://static5.comicvine.com/uploads/original/11129/111290855/5809735-3904647274-14886.png'
        }
      ]
    };
  },
  methods: {
    toggleClass(id) {
      console.log('Clicked ' + id);

      const currentState = this.active;
      this.active = !currentState;
      //   this.selectedItemIndex = id;

      if (this.selectedItemIndex === id) {
        this.active === true;
      } else if (this.selectedItemIndex === !id) {
        this.active === false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.dragonball-container {
  cursor: pointer;
  display: grid;
  padding: 20px;
  grid-template-columns: 1fr 1fr;
  //background: #666;
  border: 2px solid #666;
  grid-gap: 20px;
  margin-bottom: 20px;
  border-radius: 10px;
  -webkit-box-shadow: 10px 10px 5px 0px rgba(240, 240, 240, 1);
  -moz-box-shadow: 10px 10px 5px 0px rgba(240, 240, 240, 1);
  box-shadow: 10px 10px 5px 0px rgba(240, 240, 240, 1);
}

.dragonball-image img {
  display: grid;
  justify-content: center;
  align-items: center;
  width: 100%;
  max-width: 300px;
  border-radius: 100%;
}

ul li {
  list-style: none;
}
.hover {
  background: rgb(244, 244, 244);
  border-radius: 10px;
}
</style>

2 个答案:

答案 0 :(得分:3)

我最喜欢这样做的方法是为每个战士添加一个新密钥,并在v-for中使用该密钥。标记中唯一需要的是将:class值更改为v-for循环中战斗机的活动键。

   <li
      v-for="(dragonBallFighters, index) of dragonBallFighter"
      @click="toggleClass(dragonBallFighters.id)"
      :key=dragonBallFighters.id
      :class="{hover: dragonBallFighters.active}"
   >
    <div class="dragonball-container">
      <div class="dragonball-stats">
        <h1>{{index}}, {{dragonBallFighters.name}}</h1>
        <p>{{dragonBallFighters.race}}</p>
        <p>{{dragonBallFighters.specialAttack}}</p>
      </div>
      <div class="dragonball-image">
        <img :src="dragonBallFighters.img" :alt="dragonBallFighters.name" />
      </div>
    </div>
  </li>

然后对于Javascript,我们使用Vue.set()告诉dom我们添加了一个不在v-for知道的原始对象中的密钥。这使得vue在我们改变战斗机的活动性时正确地更新了dom。

toggleClass(id) {
  // Create variable for all fighters (name takes up less space)
  let allFigthers = this.dragonBallFighter;
  // Get the clicked fighter
  let fighter = allFigthers.find(e => e.id === id)
  // Set all fighters to have a active key of false so that they "loose focus"
  allFigthers = allFigthers.map(e => Vue.set(e, 'active', false))
  // Use Vue.set to tell vue that we updated the object and it needs to be re-rendered
  Vue.set(fighter, 'active', !fighter.active)
}

Live example

我切换活动类的方法只是执行!fighter.active。 这将转换为not {boolean}〜如果fighter.active是true 那么not true将等同于假。如果为假,not false将等于真

顺便说一句;我建议你将战士的对象重命名为dragonBallFighters。这样,v-for更有意义== <v-for="fighter in dragonBallFighters"可以将其转换为

  

对于dragonBallFighters对象中的每个战斗机。

现在,你间接地说

  

对于dragonBallFighter对象中的每个dragonBallFighters

女巫不会在舌头上漂浮;)

答案 1 :(得分:0)

Put&#34; active&#34;作为每个龙球战斗机的财产,如果它被点击并将其余部分关闭,则将其打开。

Vue的概念是使用数据并让Vue处理UI:)

OR

重命名&#34;活跃&#34;到activeID并将点击的项目的ID设置为activeID,然后仅在activeID == item.id

时应用悬停