13

This code works but is there a way to consolidate these two conditions and outputs into one line of code?

<img v-if="pointshover" :src="pointshover" :key="pointshover" class="leaderimg">
<img v-if="!pointshover" :src="leaderPoints[0].playerimg" :key="pointshover" class="leaderimg">

Basically if 'pointshover' is null then it grabs the image src from leaderPoints[0].playerimg. If 'pointshover' is not null then it is the src.

2 Answers 2

31

Option 1

Then as you want to use only one line, going with the solution proposed by @choasia with a small change.

<img :src="pointshover ? pointshover : leaderPoints[0].playerimg" :key="pointshover" class="leaderimg">

You won't need the v-if as this image is shown always, and it will have the pointshover src only when it exists and the leaderPoints[0].playerimg when it doesn't.

Option 2

If you go with the two lines code you probably should use:

<img v-if="pointshover" :src="pointshover" :key="pointshover" class="leaderimg">
<img v-else :src="leaderPoints[0].playerimg" :key="pointshover" class="leaderimg">

It's clearer what you want to accomplish if you use an else.

Option 3

You could use a computed property to bind the src.

<img :src="myImageSource" :key="pointshover" class="leaderimg">

myImageSource(){
    return this.pointshover ? this.pointshover : this.leaderPoints[0].playerimg;
}
Sign up to request clarification or add additional context in comments.

Comments

4

You can use JavaScript expressions in :src.

<img v-if="pointshover" :src="pointshover ? pointshover : leaderPoints[0].playerimg" :key="pointshover" class="leaderimg">

Comments

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.