You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 05:28:34