0

Is there a way to do something like this:

<router-link to="/">
        <img src=" :active = isExactActive ? pic_active.png : pic_inactive.png}}" /> //Somethink like this
        <div class="text">Home</div>
</router-link>

Img src should be depending on whether link is exact active or not. If active pic_active should show, if not active pic-inactive should show. How can I make this work? I am a beginner to vue and I have been searching for hours...

Thanks!

Mohammed
  • 195
  • 1
  • 3
  • 12

1 Answers1

-1

There are multiple ways to do this, but I would suggest to either use a computed property (https://v2.vuejs.org/v2/guide/computed.html) to contain the source, something like

<router-link to="/">
        <img src="{{ imageLink }}" /> <!-- Something like this -->
        <div class="text">Home</div>
</router-link>

// your component
export default {
   computed: {
       imageLink: isExactActive ? 'pic_active.png' : 'pic_inactive.png',
   }
}

or use a v-if (https://v2.vuejs.org/v2/guide/conditional.html):

<router-link to="/">
        <img v-if="isExactActive" src="pic_active.png" />
        <img v-else src="pic_inactive.png" /> <!-- Something like this -->
        <div class="text">Home</div>
</router-link>
tony19
  • 125,647
  • 18
  • 229
  • 307
Sliverious
  • 34
  • 1
  • 4
  • @Silverious Hi, Thanks for your awnser. I tried your v-if solution but it only shows the else image. isExactActive is a built-in attribut for routerlink thats why I thought it will change picture when clicked. Or am I wrong? Also I have multiple routerlinks, will all be active if one is active? – Mohammed May 17 '21 at 09:01
  • I should've recognized the package I suppose. I am currently unable to check this for myself, but I suspect you should be able to get it working using a v-slot: https://router.vuejs.org/api/#v-slot-api-3-1-0. The code is a bit more advanced but if you copy the example and replace the navlink with a span containing your img and div you should be able to get something working. – Sliverious May 17 '21 at 09:20