首页 > 解决方案 > Vuejs - 选中复选框时显示/隐藏块,当复选框是组件时

问题描述

选中或取消选中复选框时,我需要显示或隐藏块。复选框是组件,包括在布局中。选择布局中必须显示或隐藏的内容。例如:

布局页面:

<template lang="pug">

  div
    checkbox(caption="test")
    div(v-if="showExtend")
      p lorem ipsum

</template>

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

复选框组件:

<template lang="pug">
  label
     input(type="checkbox", :name="name", :checked="checked")
     span(v-html="caption")

</template>

<script>
  props: {
        caption: {
            type: String
        },
        name: {
            type: String,
            required: true
        },
        checked: {
            type: Boolean
        }
    }
</script>

标签: vue.js

解决方案


@change在复选框组件输入元素中缺少事件,在您的示例中,您有单向绑定。见:https ://forum.vuejs.org/t/custom-checkbox-component/1120/5 ,自定义v-model:https ://vuejs.org/v2/guide/components.html#Using-v-model -on-Components

复选框组件:

<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>

布局:

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

</template>

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

你可以测试它:

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>


推荐阅读