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

Vue3中如何使用vue-select实现带图片的选择器?

Vue3 实现带图片的 vue-select 自定义选项

要在Vue3中实现带图片的选择器,核心是适配Vue3的插槽语法,并使用对应版本的vue-select组件,具体步骤如下:

1. 安装Vue3兼容版vue-select

Vue3需要使用@sagalbot/vue-select的4.x版本,执行安装命令:

npm install @sagalbot/vue-select@4.x

2. 组件注册(局部或全局)

在组件中局部注册:

import { defineComponent } from 'vue'
import vSelect from '@sagalbot/vue-select'
import '@sagalbot/vue-select/dist/vue-select.css'

export default defineComponent({
  components: {
    vSelect
  },
  // ...其他代码
})

3. 修改模板代码(适配Vue3插槽语法)

Vue3废弃了slot和slot-scope属性,统一使用v-slot指令。同时组件标签从v2-select改为v-select,完整模板代码如下:

<template>
  <v-select :options="options" label="title">
    <template v-slot:option="{ option }">
      <img :src="option.url" style="width: 24px; height: 24px; margin-right: 8px;" />
      {{ option.title }}
    </template>
  </v-select>
</template>

4. 数据部分保持不变

export default defineComponent({
  data() {
    return {
      options: [
        {
          title: 'Read the Docs',
          icon: 'fa-book',
          url: 'https://codeclimate.com/github/sagalbot/vue-select'
        },
        {
          title: 'View on GitHub',
          icon: 'fa-github',
          url: 'https://codeclimate.com/github/sagalbot/vue-select'
        },
        {
          title: 'View on NPM',
          icon: 'fa-database',
          url: 'https://codeclimate.com/github/sagalbot/vue-select'
        },
        {
          title: 'View Codepen Examples',
          icon: 'fa-pencil',
          url: 'https://codeclimate.com/github/sagalbot/vue-select'
        }
      ]
    }
  }
})

关键变化说明

  • 组件标签变更:Vue3版本的组件为v-select,而非Vue2中的v2-select
  • 插槽语法更新:将slot="option"和slot-scope="option"合并为v-slot:option="{ option }",通过解构赋值直接获取当前选项对象
  • 样式引入:必须导入vue-select的官方样式文件,否则组件样式会异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 20:25:30