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

如何在BootstrapVue中实现自定义收藏图标功能

实现方案

我们可以直接基于BootstrapVue原生的<b-form-checkbox>组件自定义插槽实现,不需要额外引入第三方组件,代码量少且适配原有组件库的交互逻辑。

前置依赖

确保项目已引入Bootstrap Icons图标库,可直接通过npm安装:

npm install bootstrap-icons

然后在入口文件引入样式:

import 'bootstrap-icons/font/bootstrap-icons.css'

核心实现代码

模板部分

<template>
  <!-- 单个收藏按钮示例 -->
  <b-form-checkbox
    v-model="isFavorited"
    class="favorite-checkbox"
    no-border
    @change="handleFavoriteChange"
  >
    <template #default="{ checked }">
      <i 
        :class="checked ? 'bi bi-heart-fill text-danger' : 'bi bi-heart text-secondary'"
        class="fs-4 cursor-pointer"
      ></i>
    </template>
  </b-form-checkbox>

  <!-- 报表列表循环示例 -->
  <div class="report-list mt-4">
    <div v-for="report in reportList" :key="report.id" class="report-item d-flex align-items-center p-2 border-bottom">
      <b-form-checkbox
        v-model="report.isFavorited"
        class="favorite-checkbox me-2"
        no-border
        @change="handleReportFavorite(report)"
      >
        <template #default="{ checked }">
          <i 
            :class="checked ? 'bi bi-star-fill text-warning' : 'bi bi-star text-secondary'"
            class="fs-5 cursor-pointer"
          ></i>
        </template>
      </b-form-checkbox>
      <span>{{ report.title }}</span>
    </div>
  </div>
</template>

脚本部分

<script>
export default {
  data() {
    return {
      isFavorited: false,
      reportList: [
        { id: 1, title: '月度营收报表', isFavorited: false },
        { id: 2, title: '用户增长分析报表', isFavorited: true },
        { id: 3, title: '渠道转化报表', isFavorited: false }
      ]
    }
  },
  methods: {
    handleFavoriteChange(val) {
      // 单个收藏的业务逻辑处理
      console.log('收藏状态变更:', val)
    },
    handleReportFavorite(report) {
      // 列表项收藏的业务逻辑处理,可调用后端接口更新收藏状态
      console.log('更新报表收藏状态:', report.id, report.isFavorited)
    }
  }
}
</script>

样式部分

<style scoped>
/* 隐藏默认复选框的UI */
.favorite-checkbox .custom-control-label::before,
.favorite-checkbox .custom-control-label::after {
  display: none;
}
.cursor-pointer {
  cursor: pointer;
}
</style>

效果说明

点击图标即可切换选中/未选中状态,和复选框的交互逻辑完全一致,你可以根据需求替换爱心/星形图标,也可以自定义图标的大小、颜色:

  • 爱心样式对应类名:未选中bi bi-heart、选中bi bi-heart-fill
  • 星形样式对应类名:未选中bi bi-star、选中bi bi-star-fill

如果你项目中使用的是其他图标库,直接替换<i>标签的类名为对应图标库的选中/未选中图标类名即可,逻辑无需调整。

预期效果如下图:
收藏图标效果示例图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:36:04