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.
The directive v-if is used to conditionally render a block. The block will only be rendered if the directive's expression returns a truthy value.
To do that, Vue has a special directive, v-for . This is a built-in Vue directive that lets us include a loop inside of our template, repeating the rendering of a template feature for each item in an array.
The data option for a component is a function. Vue calls this function as part of creating a new component instance. It should return an object, which Vue will then wrap in its reactivity system and store on the component instance as $data.
Most of the time, Vue components are written using a special HTML template syntax. When you need more control than the HTML syntax allows, you can write JSX or plain JavaScript functions to define your components.
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;
}
You can use JavaScript expressions in :src
.
<img v-if="pointshover" :src="pointshover ? pointshover : leaderPoints[0].playerimg" :key="pointshover" class="leaderimg">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With