0

I have an array:

let categoryNames = [
{color: '#B8E986', background_color: '#69E974'},
{color: '#E94EDF', background_color: '#69E974'},
{color: '#29E986', background_color: '#69E974'},
{color: '#E9DB72', background_color: '#69E974'},
] 

I also have an array of boolean objects:

categoryImages: [
      {isImage1: true},
      {isImage2: false},
      {isImage3: true},
      {isImage4: false},      
    ]

I iterate through "categoryNames" array and display data.

<div
        class="category-item"
        v-for="category in categoryNames"
        :key="category.name"
        :style="{ 'background-color': category.background_color }"
      >
        <p :style="{ color: category.color }">{{ category.name }}</p>
        <img
          src="../assets/images/icons/bolt.png"
          alt=""
          class="bolt"
        />

      </div>

I have an image for every item. Image is the same

How can I show or hide image according to boolean from array "categoryImages"?

expected behavior: image 1 is shown, image 2 is hidden, image 3 is shown, image 4 is hidden

current behavior: all images are shown

EDIT: I tried to make it like this:

 <img
          src="../assets/images/icons/bolt.png"
          alt=""
          class="bolt"
          v-if="Object.values(categoryImages[categoryIndex])[0]"
        />

but it throws an error

error

1 Answer 1

1

First get the current category index:

<div v-for="(category, categoryIndex) in categoryNames"

Then add a v-if directive to your img tag:

<img v-if="Object.values(categoryImages[categoryIndex])[0]"
Sign up to request clarification or add additional context in comments.

5 Comments

I get an error: "Error in render: "TypeError: Cannot convert undefined or null to object"
Well, is categoryImages defined in data()? Is it the same length as categoryNames?
Yes, data: () => ({ isCardOnDesk: false, cardText: "sdfgdfg", questionText: "", categoryImages: [ {isImage1: false}, {isImage2: false}, {isImage3: false}, {isImage4: false}, ],
I mean, categoryImages[categoryIndex] is obviously not working, so did you add categoryIndex to your v-for directive?
Now it works! The problem was categoryImages array was less in size. Thank you a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.