dev_el
dev_el

Reputation: 2957

Conditional classes in Vue using objects inside v-for loop

I am using v-for to iterate over an array of objects inside my data. For each object I have in the array, I want a link. Each link should have their own class dependent on the Boolean hide property in their object.

But when I try to pass an object property into the class via :class="{ game.hide: hideGame }", Vue outputs an error: Parsing error: Unexpected Token .

What am I doing wrong?

<template>
  <div class="showcase-container">
    <button :class="{ leftArrow: noGames }">test</button>
    <a
      v-for="game in games"
      :key="game.id"
      :class="{ game.hide: hideGame }"
      href="#"
      >{{ game.name }}</a
    >
    <button>test</button>
  </div>
</template>

<script>
export default {
  noGames: true,
  data() {
    return {
      games: [
        {
          name: "Game 1",
          link: "https://google.com",
          id: 1,
          hide: false,
        },
        {
          name: "Game 2",
          link: "https://youtube.com",
          id: 2,
          hide: true,
        },
      ],
      noGames: true,
    };
  },
  methods: {
    showGame() {
      alert(this.game1);
    },
  },
};
</script>

<style lang="scss">
.leftArrow {
  visibility: hidden;
}
.hideGame {
  display: none;
}
</style>

Upvotes: 2

Views: 2475

Answers (2)

MartinDubeNet
MartinDubeNet

Reputation: 137

Minor note:
Your two CSS class names “game.hide” should be written “game hide” without the dot “.

So Brahim string should look like

:class="{'game hide':hideGame  }"

Upvotes: 0

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You're reversing the key/value in class attribute value, it should be :

:class="{ hideGame: game.hide  }"

generally :

:class="{ someClassName: someVueProperty  }"

if the class name contains - it should be wrapped by '' like :

  :class="{ 'link-hidden': isHidden}"

Upvotes: 3

Related Questions