欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

圖文詳解如何在vue3+vite項目中使用svg

 更新時間:2021年11月11日 15:19:12   作者:azi_  
SVG指可伸縮矢量圖形,用來定義用于網(wǎng)絡(luò)的基于矢量的圖形,下面這篇文章主要給大家介紹了關(guān)于如何在vue3+vite項目中使用svg的相關(guān)資料,需要的朋友可以參考下

今天在vue3+vite項目練習(xí)中,在使用svg時,發(fā)現(xiàn)之前的寫法不能用,之前的使用方法參考vue2中優(yōu)雅的使用svg

const req = require.context('./icons/svg', false, /\.svg$/)
const requireAll = requireContent => requireContent.keys().map(requireContent)
requireAll(req)

然后就各種資料查找,終于實現(xiàn)了,廢話不多說,直接上代碼:

stept1: 文件目錄

stept2: 安裝 svg-sprite-loader

npm install svg-sprite-loader -D
# via yarn
yarn add svg-sprite-loader -D

stept3: 創(chuàng)建svgIcon.vue文件

   <template>
  <svg :class="svgClass" v-bind="$attrs" :style="{color: color}">
    <use :xlink:href="iconName" rel="external nofollow" />
  </svg>
</template>

<script setup>


import { defineProps, computed } from "vue";

const props = defineProps({
  name: {
      type: String,
      required: true
    },
    color: {
      type: String,
      default: ''
    }
})

const iconName = computed(()=>`#icon-${props.name}`);
const svgClass = computed(()=> {
  console.log(props.name, 'props.name');
  if (props.name) {
        return `svg-icon icon-${props.name}`
      }
      return 'svg-icon'
});
</script>

<style lang='scss'>
.svg-icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  vertical-align: middle;
}
</style>

stept4: 創(chuàng)建icons文件夾,存放svg文件

stept5: 在main.js里面全局注入svg-icon組件

import { createApp } from 'vue'
import App from './App.vue'

import svgIcon from './components/svgIcon.vue'

createApp(App).component('svg-icon', svgIcon).mount('#app');

stept6: 在plugins文件夾創(chuàng)建svgBuilder.js(重點來了), ts版本參考:https://github.com/JetBrains/svg-sprite-loader/issues/434

import { readFileSync, readdirSync } from 'fs'

let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g

const hasViewBox = /(viewBox="[^>+].*?")/g

const clearReturn = /(\r)|(\n)/g

function findSvgFile(dir) {
  const svgRes = []
  const dirents = readdirSync(dir, {
    withFileTypes: true
  })
  for (const dirent of dirents) {
    if (dirent.isDirectory()) {
      svgRes.push(...findSvgFile(dir + dirent.name + '/'))
    } else {
      const svg = readFileSync(dir + dirent.name)
        .toString()
        .replace(clearReturn, '')
        .replace(svgTitle, ($1, $2) => {
          // console.log(++i)
          // console.log(dirent.name)
          let width = 0
          let height = 0
          let content = $2.replace(
            clearHeightWidth,
            (s1, s2, s3) => {
              if (s2 === 'width') {
                width = s3
              } else if (s2 === 'height') {
                height = s3
              }
              return ''
            }
          )
          if (!hasViewBox.test($2)) {
            content += `viewBox="0 0 ${width} ${height}"`
          }
          return `<symbol id="${idPerfix}-${dirent.name.replace(
            '.svg',
            ''
          )}" ${content}>`
        })
        .replace('</svg>', '</symbol>')
      svgRes.push(svg)
    }
  }
  return svgRes
}

export const svgBuilder = (path, perfix = 'icon') => {
  if (path === '') return
  idPerfix = perfix
  const res = findSvgFile(path)
  // console.log(res.length)
  // const res = []
  return {
    name: 'svg-transform',
    transformIndexHtml(html) {
      return html.replace(
        '<body>',
        `
          <body>
            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">
              ${res.join('')}
            </svg>
        `
      )
    }
  }
}

stept7: 最后在vite.config.js修改配置

import { svgBuilder } from './src/plugins/svgBuilder'; 

export default defineConfig({
  plugins: [svgBuilder('./src/icons/svg/')] // 這里已經(jīng)將src/icons/svg/下的svg全部導(dǎo)入,無需再單獨導(dǎo)入
})

總結(jié)

到此這篇關(guān)于如何在vue3+vite項目中使用svg的文章就介紹到這了,更多相關(guān)vue3+vite使用svg內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Vue實現(xiàn)倒計時小功能

    Vue實現(xiàn)倒計時小功能

    這篇文章主要為大家詳細介紹了Vue實現(xiàn)倒計時小功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • vue3+vite+ts之a(chǎn)xios的坑及解決

    vue3+vite+ts之a(chǎn)xios的坑及解決

    這篇文章主要介紹了vue3+vite+ts之a(chǎn)xios的坑及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • Vue中Vue.use()的原理及基本使用

    Vue中Vue.use()的原理及基本使用

    相信很多人在用Vue使用別人的組件時,會用到 Vue.use() ,例如:Vue.use(VueRouter)、Vue.use(MintUI),這篇文章主要給大家介紹了關(guān)于Vue中Vue.use()的原理及基本使用的相關(guān)資料,需要的朋友可以參考下
    2021-10-10
  • Vue中的事件處理詳情

    Vue中的事件處理詳情

    這篇文章主要介紹了Vue中的事件處理詳情,文章通過給按鈕綁定一個?click?事件展開詳細內(nèi)容介紹,需要的小伙伴可以參考一下
    2022-05-05
  • vue項目創(chuàng)建步驟及路由router

    vue項目創(chuàng)建步驟及路由router

    本文主要給大家分享了vue項目的創(chuàng)建步驟以及vue路由router的相關(guān)知識點,非常的實用,有需要的小伙伴可以來參考下
    2020-01-01
  • vue打包之后配置統(tǒng)一請求地址步驟詳解

    vue打包之后配置統(tǒng)一請求地址步驟詳解

    這篇文章主要為大家介紹了vue打包之后配置統(tǒng)一請求地址實現(xiàn)步驟詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-07-07
  • vue數(shù)據(jù)監(jiān)聽解析Object.defineProperty與Proxy區(qū)別

    vue數(shù)據(jù)監(jiān)聽解析Object.defineProperty與Proxy區(qū)別

    這篇文章主要為大家介紹了vue數(shù)據(jù)監(jiān)聽解析Object.defineProperty Proxy源碼示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-03-03
  • vue3+Element Plus實現(xiàn)自定義穿梭框的詳細代碼

    vue3+Element Plus實現(xiàn)自定義穿梭框的詳細代碼

    找到一個好用的vue樹形穿梭框組件都很難,又不想僅僅因為一個穿梭框在element-ui之外其他重量級插件,本文給大家分享vue3+Element Plus實現(xiàn)自定義穿梭框的示例代碼,感興趣的朋友一起看看吧
    2024-01-01
  • vue3?中的toRef函數(shù)和toRefs函數(shù)的基本使用

    vue3?中的toRef函數(shù)和toRefs函數(shù)的基本使用

    這篇文章主要介紹了vue3?toRef函數(shù)和toRefs函數(shù),文中介紹了ref和toRef的區(qū)別,ref本質(zhì)是拷貝,修改響應(yīng)式數(shù)據(jù)不會影響原始數(shù)據(jù),toRef的本質(zhì)是引用關(guān)系,修改響應(yīng)式數(shù)據(jù)會影響原始數(shù)據(jù),需要的朋友可以參考下
    2022-11-11
  • Vue.js?前端路由和異步組件介紹

    Vue.js?前端路由和異步組件介紹

    這篇文章主要介紹了Vue.js?前端路由和異步組件介紹,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-09-09

最新評論