Vue3中如何将父组件状态绑定至可复用SelectInput组件?
实现user.favoriteColor与SelectInput组件的双向绑定
在Vue 3的<script setup>语法中,通过v-model语法糖(本质是props+自定义事件)即可实现父组件状态与子组件下拉框的双向绑定,具体修改如下:
1. 更新SelectInput.vue
添加接收绑定值的prop,并在选择变化时触发更新事件:
<script setup> defineProps({ selectOptions: Array, // 接收父组件的绑定值,Vue3默认v-model对应的prop为modelValue modelValue: String }) // 定义用于更新绑定值的事件 defineEmits(['update:modelValue']) </script> <template> <select :value="modelValue" @change="$emit('update:modelValue', $event.target.value)" > <option disabled value="">Please select one</option> <option v-for="option in selectOptions" :key="option" :value="option" >{{ option }}</option> </select> </template>
为
<option>绑定:value确保选中值能正确传递给父组件。
2. 更新Home.vue
使用v-model将user.favoriteColor与SelectInput绑定:
<script setup> import { ref } from 'vue'; import SelectInput from './SelectInput.vue'; const user = ref({ name: '', favoriteColor: '', }) const selectOptions = ref(['red', 'green', 'blue', 'white', 'black']) </script> <template> <div class="user-input-container"> <div class="user-input"> <p>Favorite Color</p> <!-- 用v-model绑定user.favoriteColor --> <SelectInput :selectOptions="selectOptions" v-model="user.favoriteColor" /> <!-- 可选:添加预览查看绑定效果 --> <p>Selected Color: {{ user.favoriteColor }}</p> </div> </div> </template>
修改完成后,下拉框的选择会同步更新user.favoriteColor,父组件中user.favoriteColor的变更也会同步到下拉框的选中状态,实现双向绑定。
内容的提问来源于stack exchange,提问作者Onyx
相关产品推荐
相关产品推荐

