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

如何在Quasar框架q-btn-toggle组件中正确使用自定义SVG图标

Quasar q-btn-toggle组件自定义SVG图标不显示问题修复

问题复现代码

模板代码(Pug语法)

template(lang="pug")
  q-btn-toggle.my-custom-toggle(v-model="secondModel" color="white" text-color="primary" :options="toggleOption" size="sm")

数据配置代码

toggleOption: [
  { label: 'Table', value: 'table', slot: 'one', icon: require('@/assets/svg/toggle/Table.svg') },
  { label: 'Calendar', value: 'calendar', slot: 'two', icon: '@/assets/svg/toggle/Table.svg' }
],
secondModel: 'table'

故障原因

  • 直接在icon属性中写@/assets/xxx.svg字符串无效:@是构建工具(Vite/Webpack)的路径别名,写在普通对象字符串中不会被构建工具解析,浏览器无法识别该路径。
  • 直接传入require()返回的资源路径无效:Quasar默认会把不带前缀的icon值识别为内置图标库(Material Icons、FontAwesome等)的图标名,不会当作图片资源处理。

修复方案

方案1:使用img:前缀标记图片类图标(最简便)

Quasar的icon属性支持img:前缀,标记后会将后续传入的路径作为图片资源渲染,适配Vite和Webpack两种构建模式。

  • Vite项目写法:先通过import引入SVG资源,拼接前缀传入
// 脚本顶部引入资源
import tableSvg from '@/assets/svg/toggle/Table.svg'
import calendarSvg from '@/assets/svg/toggle/Calendar.svg'

// 配置项修改
toggleOption: [
  { label: 'Table', value: 'table', icon: `img:${tableSvg}` },
  { label: 'Calendar', value: 'calendar', icon: `img:${calendarSvg}` }
],
secondModel: 'table'
  • Webpack项目写法:给require返回的路径拼接前缀即可
toggleOption: [
  { label: 'Table', value: 'table', icon: `img:${require('@/assets/svg/toggle/Table.svg')}` },
  { label: 'Calendar', value: 'calendar', icon: `img:${require('@/assets/svg/toggle/Calendar.svg')}` }
],
secondModel: 'table'

方案2:使用插槽自定义渲染(适合需要灵活控制SVG样式的场景)

如果需要修改SVG颜色、尺寸,或者自定义选项内容,可以利用q-btn-toggle的选项插槽渲染自定义内容,模板修改如下:

template(lang="pug")
  q-btn-toggle.my-custom-toggle(v-model="secondModel" color="white" text-color="primary" :options="toggleOption" size="sm")
    template(v-slot:one)
      q-icon(name="img:@/assets/svg/toggle/Table.svg" size="1em" class="q-mr-xs")
      span Table
    template(v-slot:two)
      q-icon(name="img:@/assets/svg/toggle/Calendar.svg" size="1em" class="q-mr-xs")
      span Calendar

对应的配置项保留slot字段即可,无需再传icon属性:

toggleOption: [
  { label: 'Table', value: 'table', slot: 'one' },
  { label: 'Calendar', value: 'calendar', slot: 'two' }
],
secondModel: 'table'

注意:如果需要SVG图标跟随text-color自动变色,建议将SVG文件处理为内联svg图标注册到Quasar图标集,或直接在插槽中写入内联SVG代码。

内容的提问来源于stack exchange,提问作者Serkan Gün

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 00:45:31