Vue中使用单选按钮切换组件的实现方案咨询
Hey there! I see where the issue is with your component toggling—let's get this sorted out quickly. The main problems are with how you're binding the radio buttons and checking the v-show conditions. Here's what needs to change:
Key Issues in Your Current Code
- Radio buttons use a string value for
v-model, not an array. You've setpickedas an empty array, which works for checkboxes but not single-selection radio buttons. - Your
v-showconditions are trying to access properties onpicked(likepicked.first_toggle), butpickedshould hold the string value of the selected radio button—so you need to compare it directly to the button'svalue. - The hardcoded
checkedattribute on the second radio button is unnecessary once you set the initial value indata(v-model will handle the default selection).
Corrected Code
Here's the fixed version of your component:
Template Section
<template> <div class="wrapper"> <div class="toggle_radio"> <input type="radio" class="toggle_option" id="first_toggle" value="first_toggle" name="toggle_option" v-model="picked"> <input type="radio" class="toggle_option" id="second_toggle" value="second_toggle" name="toggle_option" v-model="picked"> <input type="radio" class="toggle_option" id="third_toggle" value="third_toggle" name="toggle_option" v-model="picked"> <label for="first_toggle"><p>Read</p></label> <label for="second_toggle"><p>Reading</p></label> <label for="third_toggle"><p>Want To Read</p></label> <div class="toggle_option_slider"> <span>Picked: {{ picked }} </span> </div> </div> <!-- Use direct value comparison for v-show --> <app-read v-show="picked === 'first_toggle'"></app-read> <app-reading v-show="picked === 'second_toggle'"></app-reading> <app-want-to-read v-show="picked === 'third_toggle'"></app-want-to-read> </div> </template>
Script Section
<script> import Read from './Read.vue' import Reading from './Reading.vue' import WantToRead from './Want_To_Read.vue' export default { data(){ return { // Set picked to a string, with the default selected value (matches second radio button) picked: 'second_toggle' }; }, components: { appRead: Read, appReading: Reading, appWantToRead: WantToRead } } </script>
What Changed?
pickeddata type: Switched from an array to a string, which is the correct type for radio buttonv-modelbinding.v-showconditions: Updated to comparepickeddirectly to the radio button'svalue(e.g.,picked === 'first_toggle'), so the correct component shows when its corresponding radio button is selected.- Removed hardcoded
checked: The default selection is now handled by settingpicked: 'second_toggle'indata, which is cleaner and aligns with Vue's reactive approach.
This should make your radio buttons correctly toggle between the Read, Reading, and WantToRead components!
内容的提问来源于stack exchange,提问作者Eliza K.
相关产品推荐
相关产品推荐

