如何用VueJS实现单选按钮切换显示/隐藏datetime-local等输入元素?
嘿,这个需求用Vue.js实现超简单的,核心就是利用条件渲染来控制那两个输入框的显示隐藏~我结合你的代码片段整理了完整的实现方案,你可以直接参考:
完整实现代码(Vue 2/3 Options API 版本)
<template> <div class="row"> <div class="col"> <!-- 给单选按钮绑定数据属性,设置明确的value值 --> <input type="radio" name="paper" value="live" v-model="selectedPaperType"> Live Paper <br> <input type="radio" name="paper" value="normal" v-model="selectedPaperType"> Normal Paper <br> <!-- 用v-if控制额外输入框的显示 --> <div v-if="selectedPaperType === 'live'" style="margin-top: 10px;"> Live on <input type="datetime-local" class="form-control"> <br> Duration <input type="time" class="form-control"> </div> </div> </div> </template> <script> export default { data() { return { // 默认选中Normal Paper,你也可以改成'live'或者空值 selectedPaperType: 'normal' } } } </script>
关键知识点解释
v-model绑定单选按钮:
我给每个单选按钮设置了明确的value值(live和normal),并用v-model绑定到selectedPaperType这个数据属性上。用户切换单选按钮时,这个属性会自动同步为选中项的value值,这是实现条件判断的核心。条件渲染控制显示隐藏:
用v-if="selectedPaperType === 'live'"包裹需要隐藏的输入框,只有当用户选中Live Paper时,这部分DOM才会被渲染出来;选Normal Paper时,这部分DOM会被移除。如果你只是想隐藏而不是销毁DOM,可以换成v-show(它会通过CSS的display: none来控制显示)。
Vue 3 组合式API版本(可选)
如果你用的是Vue 3的<script setup>语法,代码可以改成这样:
<template> <!-- 模板部分和上面完全一样 --> <div class="row"> <div class="col"> <input type="radio" name="paper" value="live" v-model="selectedPaperType"> Live Paper <br> <input type="radio" name="paper" value="normal" v-model="selectedPaperType"> Normal Paper <br> <div v-if="selectedPaperType === 'live'" style="margin-top: 10px;"> Live on <input type="datetime-local" class="form-control"> <br> Duration <input type="time" class="form-control"> </div> </div> </div> </template> <script setup> import { ref } from 'vue' // 用ref创建响应式变量 const selectedPaperType = ref('normal') </script>
这样就能完美实现你要的功能啦~
内容的提问来源于stack exchange,提问作者margherita pizza
相关产品推荐
相关产品推荐

