[Vuejs]-Vuejs โ€“ Show/Hide block when checkbox checked, when checkbox is component

0๐Ÿ‘

โœ…

You are missing @change event in checkbox component input element, in your example you have 1-way binding. See: https://forum.vuejs.org/t/custom-checkbox-component/1120/5, custom v-model: https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components

Checkbox component:

<template lang="pug">
  label
     input(type="checkbox", :name="name", :checked="value", @change="$emit('input', $event.target.checked)")
     span(v-html="caption")
</template>
<script>
  props: ["caption", "name", "value"]
</script>

Layout:

<template lang="pug">
  div
    checkbox(caption="test", v-model="showExtend")
    div(v-if="showExtend")
      p lorem ipsum

</template>

<script>
  data() {
    return: {
      showExtend: false
    }
  }
</script>

You can test it:

new Vue({el:'#layout', data:{showExtend:false}})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>
<template id="checkbox">
  <label>
     <input type="checkbox" :name="name" :checked="value" @change="$emit('input', $event.target.checked)">
     <span v-html="caption"></span>
  </label>
</template>
<script>
  Vue.component('checkbox', {template:'#checkbox', props: ["caption", "name", "value"]})
</script>
<div id="layout">
  <checkbox caption="test" v-model="showExtend"></checkbox>
  <div v-if="showExtend">lorem ipsum</div>
</div>

Leave a comment