天天看點

Vue項目中優雅的使用svg圖表

Svg的使用

第一步肯定要下載下傳安裝

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

然後在src下面建立檔案夾

Vue項目中優雅的使用svg圖表

svg裡面放的是使用阿裡矢量圖示庫裡的下載下傳圖示檔案

附圖示網址:https://www.iconfont.cn/home/index?spm=a313x.7781069.1998910419.2

下載下傳檔案後複制粘貼到svg檔案下

Vue項目中優雅的使用svg圖表

index.js中檔案代碼如下:不用糾結直接複制

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg元件
//挂載到全局
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
           

在vue.config.js檔案中配置如下:

Vue項目中優雅的使用svg圖表

代碼附上

chainWebpack: config => {
      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();

      config.module
        .rule('images')
        .test(/\.(png|jpg|gif)$/)
        .use('url-loader')
        .loader('url-loader')
        .options({
            name: 'images/[name].[ext]',
            limit: 1000
        })
        .end();
    }
           

然後components檔案下建立SvgIcon.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>
           

在main.js中導入一下

import ‘./icons’

任意位置使用:

注意:icon-class的名字是根據svg下面的檔案名字來寫的,不可以自己随便寫