1
votes

I want to show and hide button on click in Vue js. It's working fine. When I click the 'show' button it will expand and button name will change to 'hide'. Then again click the hide button it will show the 'show' button without images. Before Click: https://prnt.sc/p7pjil

After Click(I need to change the button text to hide or some other name): https://prnt.sc/p7pj9b

    <div id="app">

      <h1>Click the Button to Show or Hide</h1>
      <button class="btn-primary" v-on:click="isHidden = !isHidden">Click to Show the Images</button>

      <img src="images/7.jpg" v-if="!isHidden">
      <img src="images/8.jpg" v-if="!isHidden">
      <img src="images/9.jpg" v-if="!isHidden">

    </div>

    <script>
    var app = new Vue({
      el: '#app',
      data: {
        isHidden: true
      }
    });
    </script>
2

2 Answers

2
votes

I guess, you just want to switch the text? You can use <template v-if> for that. v-if conditionally shows an element with its content. <template> is an element which will not be rendered in the final HTML, just its content.

<div id="app">

  <h1>Click the Button to Show or Hide</h1>
  <button class="btn-primary" v-on:click="isHidden = !isHidden">
    <template v-if="isHidden">Click to Show the Images</template>
    <template v-else>Click to Hide the Images</template>
  </button>

  <img src="images/7.jpg" v-if="!isHidden">
  <img src="images/8.jpg" v-if="!isHidden">
  <img src="images/9.jpg" v-if="!isHidden">

</div>

<script>
var app = new Vue({
  el: '#app',
  data: {
    isHidden: true
  }
});
</script>

You could also use the the ternary operator, if you only have one simple condition. Ternary operators should not be used with nested conditions.

<button class="btn-primary" v-on:click="isHidden = !isHidden">
  {{ isHidden ? 'Click to Show the Images' : 'Click to Hide the Images' }}
</button>
1
votes

I think this should help

var app = new Vue({
      el: '#app',
      data: {
        isHidden: true
      }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<h1>Click the Button to Show or Hide</h1>
      <button class="btn-primary" v-on:click="isHidden = !isHidden">{{ isHidden ? 'Click to Show the Images' : 'Click to Hide the Images' }}</button>
<div>
      <img width="100" src="https://images.freeimages.com/images/large-previews/ffa/water-lilly-1368676.jpg" v-if="!isHidden">
      <img width="100" src="https://images.freeimages.com/images/large-previews/ffa/water-lilly-1368676.jpg" v-if="!isHidden">
      <img width="100" src="https://images.freeimages.com/images/large-previews/ffa/water-lilly-1368676.jpg" v-if="!isHidden">
</div>
    </div>