Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs :src with a v-if condition

Tags:

vue.js

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.

like image 349
gvon79 Avatar asked Oct 25 '17 00:10

gvon79


People also ask

What does V if do in Vue?

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.

What feature of Vue can be used to repeat an element using a collection of data?

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.

What is VUE JS data ()?

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.

Do you need HTML for Vue?

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.


2 Answers

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;
}
like image 91
Mikel Díez Buil Avatar answered Oct 12 '22 22:10

Mikel Díez Buil


You can use JavaScript expressions in :src.

<img v-if="pointshover" :src="pointshover ? pointshover : leaderPoints[0].playerimg" :key="pointshover" class="leaderimg">
like image 20
choasia Avatar answered Oct 12 '22 22:10

choasia