Home > database >  How to hide the content on checkbox click in Vuejs?
How to hide the content on checkbox click in Vuejs?

Time:12-03

new Vue({
      el: '#selector',
      data: {
        checked: false,
        unchecked: true
      },
      methods: {
        hidecont() {
          this.checked = !this.unchecked;
        }
      });
<div id="selector">
  <div class="checkbox">
    <label><input type="checkbox" v-model="checked" @click="hidecont" >Options</label>
  </div>
  <div class="container" id="app-container" v-if="unchecked">
    <p>Text is visible</p>
  </div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I have toggled using method like check=!checkedd but still i am unable to hide the content.

Initially checkbox and text content should be visible. So once user clicked on checkbox, the content will be in hide.

CodePudding user response:

data property must be function:

new Vue({
  el: '#selector',
  data() {
    return {
      checked: false,
    }
  },
  methods: {
    hidecont() {
      this.checked = !this.checked;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="selector">
  <div class="checkbox">
    <label><input type="checkbox" v-model="checked" @click="hidecont" >Options</label>
  </div>
  <div class="container" id="app-container" v-if="!checked">
    <p>Text is visible</p>
  </div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Several variables are not required to handle this logic.
You can just save the 'checked' variable, and it's bidirectional binding, when checkbox is checked, it will be true.
Here is my code.

new Vue({
      el: '#selector',
      data: {
        checked: false,
      },
    })
<div id="selector">
  <div class="checkbox">
    <label><input type="checkbox" v-model="checked">Options</label>
  </div>
  <div class="container" id="app-container" v-if="checked">
    <p>Text is visible</p>
  </div>
</div>

CodePudding user response:

new Vue({
  el: '#selector',
  data() {
    return {
      checked: false,
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="selector">
  <div class="checkbox">
    <label><input type="checkbox" v-model="checked" @click="hidecont" >Options</label>
  </div>
  <div class="container" id="app-container" v-if="!checked">
    <p>Text is visible</p>
  </div>
</div>

I just replaced v-if="!checked" in content div

  • Related