bbsimonbb
bbsimonbb

Reputation: 28992

v-if not behaving as expected

I have a Vue component that I want to appear sometimes in one spot, sometimes in another. So I give it a property which I test in a v-if directive on the root of template. I have two custom tags in my markup, and assume that I'll get two distinct instances of my component. To my surprise, the component renders twice, even when one of the properties is false. What is going on here?

markup

<div id='vueRoot'>
  <now-you-see-me show-me='true'></now-you-see-me>
  <now-you-see-me show-me='false'></now-you-see-me>
</div>

js

Vue.component('now-you-see-me',{
  template : `<div v-if='showMe'>I only want ONE **{{showMe}}**</div`,
  props : ['showMe']
})
vm = new Vue({
  el : '#vueRoot'
})

running here

Upvotes: 0

Views: 72

Answers (2)

Tom Doodler
Tom Doodler

Reputation: 1559

You are passing the show-me property as a string, when you actually want to pass it as a boolean. Instead of show-me="..." write v-bind:show-me="..." (or :show-me="..."). Everything inside the " then will be interpreted as Javascript instead of a string.

https://jsfiddle.net/aw3bup8u/1/

Upvotes: 0

Terry
Terry

Reputation: 66103

For true and false bindings, you have to use v-bind:show-me instead of just show-me, because the attribute's value will otherwise be evaluated as a string instead of a boolean exprsesion, e.g.:

<now-you-see-me v-bind:show-me='true'></now-you-see-me>

...or if you're more comfortable with shorthands:

<now-you-see-me :show-me='true'></now-you-see-me>

See proof-of-concept below:

Vue.component('now-you-see-me',{
  template : `<div v-if='showMe'>I only want ONE **{{showMe}}**</div>`,
  props : ['showMe']
})
vm = new Vue({
  el : '#vueRoot'
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>

<div id='vueRoot'>
  <now-you-see-me :show-me='true'></now-you-see-me>
  <now-you-see-me :show-me='false'></now-you-see-me>
</div>

Upvotes: 1

Related Questions