簡體   English   中英

如何在 vue-cli 構建的 vue 項目中使用 bootstrap-icons 作為 svgs

[英]How to use bootstrap-icons as svgs in a vue project build by vue-cli

我嘗試在我的 vue 項目中使用 bootstrap-icons 庫,現在我只導入 CSS 文件,這樣我就可以用作圖標字體(“i”標簽)。但是我想將它們用作 svgs,所以我可以使用線性-顏色填充的漸變。

我安裝了 bootstrap-icons 到我的項目中

npm i bootstrap-icons

並嘗試按照網站上的說明使用它們:

<svg class="bi" width="32" height="32" fill="currentColor">
  <use xlink:href="bootstrap-icons.svg#heart-fill"/>
</svg>

它不起作用,我嘗試對 xlink:href 使用 require() 或使用 v-bind 將值鏈接到 var,它們都不起作用,拋出錯誤“找不到模塊”或“獲取 404”。 我試圖將 bootstrap-icons 文檔復制到 node_modules 之外並將其放在根目錄下,將 xlink:href 的值更改為“bootstrap-icons/bootstrap-icons.svg#heart-fill”,仍然無法正常工作。

我是 vue 的菜鳥,我用 vue-cli 構建了這個項目。 我無法弄清楚這個問題是怎么回事,也沒有在 Inte.net 上找到解決方案。 有沒有人遇到過同樣的問題?

static 鏈接

您可以使用~快捷方式來引用node_modules中的資產(參見此處):

<svg class="bi" width="32" height="32" fill="currentColor">
  <use xlink:href="~/bootstrap-icons/bootstrap-icons.svg#heart-fill"/>
</svg>

動態鏈接

如果您需要動態綁定,您可以使用require返回所需 svg 文件路徑的事實:

<template>
  <svg class="bi" width="32" height="32" fill="currentColor">
    <use :xlink:href="`${iconUrl}`"/>
  </svg>
</template>

<script>
const iconPath = require('bootstrap-icons/bootstrap-icons.svg');

export default {
  name: 'App',
  data() {
    return {
      iconUrl: iconPath + '#heart-fill'
    };
  }
};
</script>

你可以用 import 而不是 require 做同樣的事情:

import iconPath from 'bootstrap-icons/bootstrap-icons.svg'

如果您想知道此行為的定義位置,您可以按照此處所述檢查您的默認 vue-cli webpack-config。

字體

雖然這不是你要求的,但你可以使用 CSS 圖標字體而不是 svg:

<template>
  <i :class="iconClass" style="font-size: 32px;"></i>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      iconClass: 'bi-heart-fill'
    };
  }
};
</script>

<style>
  @import "bootstrap-icons/font/bootstrap-icons.css";
</style>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM