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

如何为Vue/Vuetify的Autocomplete自动完成列表添加hover悬停功能?

你当前代码的核心问题是插槽使用错误:你绑定@mouseenter的selection插槽是用来定义输入框内已选中项的渲染模板,不是下拉展开后的候选列表模板,因此悬停下拉选项不会触发事件。

修正后的完整实现

<template>
  <v-autocomplete
    v-model="selected"
    dense
    outlined
    hide-details
    return-object
    background-color="white"
    light
    :placeholder="placeholder"
    hide-no-data
    style="width: 500px"
    :loading="loading"
    :search-input.sync="query"
    :items="items"
    clearable
  >
    <!-- 用item插槽自定义下拉列表的每个选项 -->
    <template v-slot:item="{ item }">
      <v-list-item @mouseenter="doFunnyStuff(item)">
        <v-list-item-content>
          <v-list-item-title>{{ item.text }}</v-list-item-title>
        </v-list-item-content>
      </v-list-item>
    </template>
    <!-- 如果需要保留原来的选中项显示样式可以保留该插槽,不需要可直接删除 -->
    <template v-slot:selection="{ item }">
      <v-list-item>
        <v-list-item-content>
          <v-list-item-title>{{ item.text }}</v-list-item-title>
        </v-list-item-content>
      </v-list-item>
    </template>
  </v-autocomplete>
</template>

<script>
export default {
  data() {
    return {
      selected: null,
      query: '',
      loading: false,
      placeholder: '请选择',
      items: [
        { text: '选项1', value: 1 },
        { text: '选项2', value: 2 },
        { text: '选项3', value: 3 }
      ]
    }
  },
  methods: {
    doFunnyStuff(hoverItem) {
      // 此处可直接拿到悬停项的完整数据做后续处理
      console.log('当前悬停项:', hoverItem)
    }
  }
}
</script>

关键修改说明

  • 替换插槽为item:这是v-autocomplete专门用于自定义下拉候选列表每一项的插槽,绑定的@mouseenter事件会在鼠标悬停到对应下拉项时触发,可拿到完整的当前悬停项数据
  • 修正了原代码的语法错误:删除{{ item.text }}}多余的大括号、删除末尾重复的</template>标签
  • 采用Vue官方推荐的v-slot写法替代已废弃的slot/slot-scope语法,兼容性更好

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:24:02