0

How to conditionally bind to attributes in vue?

the v-bind directive:

Something like this given below:

<img :src=" status = true ? 'open.svg' : 'close.svg'">

In angular this is possible. I just wanted to know whether this is possible in vue.

Or is there a way to write javascript code like the one above in the template itself (ternary ops)?

1
  • You should probably rather have a computed property instead of sticking this expression into the template. Commented Sep 3, 2020 at 13:09

3 Answers 3

2

You can do this:

<img :src="status ? 'open.svg' : 'close.svg'" >

Or set it as a computed property:

<img :src="imgSrc" >
computed:{
  imgSrc(){
    return (this.status) ? 'open.svg' : 'close.svg'
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

simply try this

<img :src="status ? 'open.svg' : 'close.svg'">

in your code status = true is assignment operator you should use comparison operator like this status == true

1 Comment

as Majed Badawi suggested. the computed property will be always a good option
0

You can use status == true instead of status = true.

Just try this.

var vMain = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    status: true,
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <img :src='status == true ? "https://dummyimage.com/100x100/F00/fff" : "https://dummyimage.com/100x100/0F0/fff"'><br />
  <button onclick='vMain.status = ! vMain.status;'>Switch Status</button>
</div>

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.