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

如何让v-select返回选中字符串并触发父组件函数?

解决方案

1. 修复子组件ValidWordList的逻辑问题

先修正子组件的props错误,再添加事件触发逻辑实现值的传递:

<template>
  <!-- 绑定v-select的change事件,触发自定义事件传递选中值 -->
  <v-select 
    :items="items" 
    :label="labelText"
    @change="handleSelect"
  ></v-select>
</template>

<script setup lang="ts">
import type { PropType } from 'vue'

// 修正props定义,items默认值应为空数组(原代码用空字符串属于类型错误)
const props = defineProps({
  items: {
    type: Array as PropType<string[]>,
    default: () => []
  },
  labelText: {
    type: String,
    default: ' Words'
  }
})

// 声明自定义事件,用于向父组件传递选中值
const emit = defineEmits<{
  select: [value: string]
}>()

// 处理v-select的选中事件,触发自定义事件传递值
const handleSelect = (selectedValue: string) => {
  emit('select', selectedValue)
}
</script>

2. 父组件绑定事件接收值

在父组件调用ValidWordList时,绑定自定义的@select事件,关联父组件的select函数:

<template>
  <ValidWordList
    :items="answer.WordList"
    :labelText="answer.WordList.length + ' Words'"
    @select="select"
  />
</template>

<script setup lang="ts">
import ValidWordList from './ValidWordList.vue'
import { ref } from 'vue'

// 示例父组件数据,根据实际情况调整
const answer = ref({
  WordList: [],
  value: ''
})

function select(word: string) {
  console.log(word)
  answer.value.value = word
}
</script>

关键说明

  • 子组件必须通过defineEmits声明自定义事件,才能把内部v-select的选中值透传给父组件,直接在父组件绑定@input/@change不生效是因为子组件没有向外暴露这些事件。
  • Vuetify的v-select在items为字符串数组时,@change事件会直接返回选中的字符串,无需额外处理。

内容的提问来源于stack exchange,提问作者KoroE

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 22:22:46