vite2-vue3使用svg圖標(biāo)

vite 下載入 svg 圖標(biāo)

  1. 安裝插件:vite-plugin-svg-icons:https://www.npmjs.com/package/vite-plugin-svg-icons
npm i vite-plugin-svg-icons -D
  1. vite.config.js中配置
import viteSvgIcons from 'vite-plugin-svg-icons'
import path from 'path'

export default () => {
  return {
    plugins: [
      viteSvgIcons({
        // Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), 'src/icons')],
        // Specify symbolId format
        symbolId: 'icon-[dir]-[name]'
      })
    ]
  }
}
  1. main.js中加入如下代碼:
import 'virtual:svg-icons-register'
  1. 新建 vue 組件:/src/components/SvgIcon.vue
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :href="symbolId" />
  </svg>
</template>

<script>
  import { defineComponent, computed } from 'vue'

  export default defineComponent({
    name: 'SvgIcon',
    props: {
      prefix: {
        type: String,
        default: 'icon'
      },
      name: {
        type: String,
        required: true
      },
      className: {
        type: String,
        default: ''
      }
    },
    setup(props) {
      const symbolId = computed(() => `#${props.prefix}-${props.name}`)
      const svgClass = computed(() => {
        if (props.className) {
          return `svg-icon ${props.className}`
        }
        return 'svg-icon'
      })
      return { symbolId, svgClass }
    }
  })
</script>
<style scope>
  .svg-icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.1em; /* 因icon大小被設(shè)置為和字體大小一致,而span等標(biāo)簽的下邊緣會和字體的基線對齊,故需設(shè)置一個(gè)往下的偏移比例,來糾正視覺上的未對齊效果 */
    fill: currentColor; /* 定義元素的顏色,currentColor是一個(gè)變量,這個(gè)變量的值就表示當(dāng)前元素的color值,如果當(dāng)前元素未設(shè)置color值,則從父元素繼承 */
    overflow: hidden;
  }
</style>
  1. src 目錄下建立 icons 目錄存放 svg 圖標(biāo)
# src/icons
- back.svg
  1. 頁面使用
<header>
  <SvgIcon name="back" className="back" @click="backHome"></SvgIcon>
  <h2 class="title">我的</h2>
</header>

<script>
  ...
  setup() {
    const backHome = () => {
      router.go(-1)
    }
    return {
      backHome
    }
  }
</script>
<style lang="scss" scoped>
  header {
    height: 0.4rem;
    background-color: #ccc;
    position: relative;
    .back {
      position: absolute;
      left: 0.1rem;
      top: 0.1rem;
      font-size: 0.18rem;
      color: #f60; /* 這里定義圖標(biāo)的顏色 */
    }
    .title {
      margin: 0;
      text-align: center;
      line-height: 0.4rem;
    }
  }
</style>
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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