vue组件中通过emits实现下拉菜单选中事件回调:子组件声明并触发select事件,父组件用@select监听接收参数;支持v-model同步时还需emit update:modelvalue。

Vue 组件中通过 emits 实现下拉菜单选中事件回调,核心是:子组件用 emit 主动触发事件,父组件用 v-on(或 @)监听并接收参数。
1. 子组件定义 emits 并触发选中事件
在下拉菜单子组件(如 SelectDropdown.vue)中:
分析 Vue 3 Composition API 使用情况——审计响应式模式、可组合函数设计、ref 与 reactive 的选择、计算属性、watcher 使用及组件……
- 显式声明
emits: ['update:modelValue', 'select'](推荐 Vue 3 Composition API 写法) - 当用户点击某一项时,调用
emit('select', item),把选中的数据传出去 - 如果同时支持 v-model,可额外 emit
'update:modelValue'保持响应式同步
export default {
name: 'SelectDropdown',
props: {
modelValue: [String, Number],
options: Array
},
emits: ['update:modelValue', 'select'],
setup(props, { emit }) {
const handleItemClick = (item) => {
emit('select', item); // 触发自定义选中事件
emit('update:modelValue', item.value); // 同步 v-model
};
return { handleItemClick };
}
}
2. 父组件监听 select 事件并处理回调
在使用该下拉组件的父组件中,用 @select 绑定事件处理器:
- 参数直接接收子组件 emit 的值(如整个选项对象或仅 id/value)
- 可在回调里执行业务逻辑:更新状态、请求接口、校验等
<selectdropdown :options="cityOptions" v-model="selectedCity"></selectdropdown>
// script 中
const onCitySelected = (item) => {
console.log('选中城市:', item.label, item.value);
// 比如触发搜索、更新表单字段、记录埋点等
};
3. 可选:用 defineEmits 更精准地声明事件(Vue 3 script setup)
若使用 <script setup></script>,推荐用 defineEmits 显式声明,并支持类型检查(尤其搭配 TypeScript):
const emit = defineEmits({
select: (item) => {
return item && typeof item === 'object' && 'value' in item;
},
'update:modelValue': (value) => true
});
const handleSelect = (item) => {
emit('select', item);
emit('update:modelValue', item.value);
};
4. 注意事项
- 事件名避免用驼峰(如
itemSelect),推荐短横线格式(item-select)或小写(select),便于模板中使用@item-select - 不要在子组件里直接修改
props.modelValue,必须通过emit('update:modelValue')通知父组件更新 - 如果只是简单透传选中值,
@select和v-model可共存,互不干扰
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!









