如何在vue中使用svg


1、安裝依賴

npm install svg-sprite-loader --save-dev

2、在config文件中配置

 
         
   const path = require('path');
  
  function resolve(dir) {
    return path.join(__dirname, dir)
  }



chainWebpack(config) {
// set svg-sprite-loader config.module .rule('svg') .exclude.add(resolve('src/icons')) .end() config.module .rule('icons') .test(/\.svg$/) .include.add(resolve('src/icons')) .end() .use('svg-sprite-loader') .loader('svg-sprite-loader') .options({ symbolId: 'icon-[name]' }) .end() }

3、在src/components下新建文件夾及文件SvgIcon/index.vue,index.vue中內容如下

index.vue中的代碼如下

<template>
  <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName"/>
  </svg>
</template>
 
<script>
  export default {
    name: 'SvgIcon',
    props: {
      iconClass: {
        type: String,
        required: true
      },
      className: {
        type: String,
        default: ''
      }
    },
    computed: {
      iconName() {
        return `#icon-${this.iconClass}`
      },
      svgClass() {
        if (this.className) {
          return 'svg-icon ' + this.className
        } else {
          return 'svg-icon'
        }
      }
    }
  }
</script>
 
<style scoped>
  .svg-icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }
</style>

4、在src下新建icons文件夾,及icons文件夾下svg文件夾、index.js文件, index.js文件內容如下

 

其中index.js代碼如下:

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg組件
 
// register globally
Vue.component('svg-icon', SvgIcon)
 
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

5、在main.js中引入

import '@/icons' // icon

6、在項目中使用

 在 阿里icon適量圖庫隨便下載個svg格式的圖,

在svg文件夾下,創建一個test.svg文件,將復制下來的svg代碼貼進去

在項目中使用

<svg-icon icon-class="test"></svg-icon>

效果:

 

vue-cli2的項目中如何引入

同樣的上面的文件引入方式還是一樣的:一樣需要安裝

npm install svg-sprite-loader --save-dev

在webpack.base.conf.js中加上:

rules中:

           {
                test: /\.svg$/,
                loader: 'svg-sprite-loader',
                include: [resolve('src/icons')],
                options: {
                  symbolId: 'icon-[name]' // name代表圖標的名字
                }
            }

注意:由於vue-cli默認情況下會使用 url-loader 對svg進行處理(如下代碼),會將它放在/img 目錄下,所以這時候我們引入svg-sprite-loader 會引發一些沖突。我們可以使用exclude: [resolve('src/icons')],讓url-loader只處理除此文件夾之外的svg。

{
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    exclude: [resolve('src/icons')], // 使用exclude排除src/icons,讓url-loader只處理除此文件夾之外的svg
    options: {
      limit: 10000,
      name: utils.assetsPath('img/[name].[hash:7].[ext]')
    }
}

然后,就可以愉快在vue-cli2搭建的項目中使用svg了,使用方式和上訴相同

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM