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

Vue3自定义Select组件emit传值异常:收到Event对象而非文本值

Vue3自定义Select组件传递值异常:接收到Event对象而非选项值

问题代码

Select组件

<template>
  <select
    @change="change($event)"
    class="shadow mb-3 appearance-none border rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
  >
    <option hidden selected>Select option</option>
    <option v-for="item in props.items" :value="item.value" :key="item.id">
      {{ item.text }}
    </option>
  </select>
</template>

<script lang="ts">
export default {
  name: "Select",
  props: {
    items: { type: Object, default: undefined },
  },
  setup(props, { emit }) {
    const change = (event: any) => {
      emit("change", event.target.value);
    };
    return {
      props,
      change,
    };
  },
};
</script>

主组件代码

<Select @change.once="change" :items="types" />

<script lang="ts">
setup(){
     function change(value: any) {
          type.value = value;
    }
return onChange
}
</script>

问题原因及修复方案

1. 主组件函数返回名错误

主组件setup中定义的处理函数是change,但return的却是onChange,模板无法找到正确的绑定函数,导致Vue默认传递原生Event对象。

修正后主组件代码:

<Select @change.once="change" :items="types" />

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

export default {
  components: { Select },
  setup(){
    const type = ref('')
    function change(value: any) {
      type.value = value;
    }
    // 返回正确的函数名
    return { type, change }
  }
}
</script>

2. Select组件Props类型错误

items用于循环渲染选项,类型应该是Array而非Object,同时默认值设为空数组更合理:

修正后Select组件Props代码:

props: {
  items: { 
    type: Array,
    default: () => []
  },
},

总结

  • 核心问题是主组件返回的函数名与定义不符,导致事件处理函数未正确绑定,最终接收到原生Event对象。
  • 同时修正Select组件的Props类型,避免因类型不匹配引发的潜在问题。

内容的提问来源于stack exchange,提问作者El Hombre Sin Nombre

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 18:30:40