vue.js - 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>
解决方案
您@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>
推荐阅读
- sql-server - 在 Azure SQL 上运行非常缓慢的外部表上选择
- javascript - 使用扩展运算符深度合并对象
- actionscript-3 - Distriqt GameServices ANE - Apple 游戏中心问题
- php - 如何为 DISTINCT COUNT 的输出创建新表以按行而不是按列分布?
- groovy - Groovy - 向 Closure 添加缺失的方法
- python - Zapier 格式化程序用户名使用 Python
- typescript - 具有可选特定值的混合类型索引签名
- javascript - 通过表单将 Cookie 值传递给 PHP
- laravel - 使用 HTML Builder 时使用日期范围过滤 - yajra Datatables
- python - 根据数据框整数列值创建 sns.factorplot 的多个子图