vue中如何引入一個文件中的所有icon

1.下載完svg文件后,我把它放在了src/assets/icons
2.使用import引用

import x from "@/assets/icons/labels.svg";
console.log(x);

3.此時編輯器會報錯,如下圖

錯誤.png

4.解決的方法是在shims-vue.d.ts文件中添加以下幾行代碼

declare module "*.svg" {
  const content: string;
  export default content;
}

5.然后,用現(xiàn)在最流行的引用svg的方法:svg-sprite-loader,安裝loader

yarn add svg-sprite-loader -D

6.找到vue.config.js文件,添加下面的代碼

/* eslint-disable @typescript-eslint/no-var-requires */
// eslint-disable-next-line @typescript-eslint/no-var-requires
//如果你用的是vs code,有報錯,并且報錯的地方和下面代碼中波浪線的位置一致,此時你可以添加上面兩行注釋,如果沒有報錯,就不用添加

const path = require('path')
              ~~~~~~~~~~~~~~



module.exports = {
  lintOnSave: false,
  chainWebpack: config =>{
    const dir = path.resolve(__dirname,'src/assets/icons')
    config.module
    .rule('svg-sprite')
    .test(/\.svg$/)
    .include.add(dir).end() 
    .use('svg-sprite-loader').loader('svg-sprite-loader').options({extract:false}).end()
      config.plugin('svg-sprite').use(require('svg-sprite-loader/plugin'), [{plainSprite: true}])
                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  config.module.rule('svg').exclude.add(dir)  
  }
}

7.此時就可以使用svg了,如下

      <svg>
        <use xlink:href="#labels" />
      </svg>

此時我們引用的是單個svg的引用,如何實現(xiàn)引用icons下的所有svg呢?
我們需要把svg都封裝到icons組件中

1.components里面新建一個Icons.vue組件
2.我在組件中是這樣寫的:

<template>
  <div>
    <svg class="icon">
      <use :xlink:href="'#' + name" />    ////傳過來的name必須要加#,
    </svg>
  </div>
</template>

<script lang="ts">
const importAll = (requireContext: __WebpackModuleApi.RequireContext) =>
  requireContext.keys().forEach(requireContext);
try {
  importAll(require.context("../assets/icons", true, /\.svg$/));
} catch (error) {
  console.log(error);
}
/////上面這幾句代碼是關(guān)鍵


export default {
  props: ["name"],      
  name: "Icons",
};
</script>

<style lang="scss" scoped>
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;      ////iconfont的官網(wǎng)中的默認(rèn)樣式
  fill: currentColor;
  overflow: hidden;
}
</style>

3.然后在main.js中注冊icons這全局組件個,
4.使用時直接<Icons name = "demo" />即可

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容