Vue中使用svg

1,683 阅读1分钟

创建 SvgIcon 组件

<template>
  <svg class="svg-icon"
       aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script>
export default {
  name: "icon-svg",
  props: {
    iconClass: {
      type: String,
      required: true
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.iconClass}`;
    }
  }
};
</script>

<style>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

使用svg-sprite

需要借助svg-sprite-loader,将多个svg打包成 svg-sprite。

在vue-cli中使用svg-sprite-loader,需要修改loader。

// 在vue-cli 2.x中使用,在webpack.base.cong.js中修改
module: {
    rules: [
        {
            test: /\.svg$/,
            loader: 'svg-sprite-loader',
            include: [resolve('src/icons')],
            options: {
              symbolId: 'icon-[name]'
            }
        },
        {
            test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
            loader: 'url-loader',
            exclude: [resolve('src/icons')],
            options: {
              limit: 10000,
              name: utils.assetsPath('img/[name].[hash:7].[ext]')
            }
        },
    ]
}


// 在vue-cli 3中使用,在vue-config.js中修改
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();
}

自动导入

在src下创建一个icons的文件夹,在icons文件夹下创建svg文件夹,用于存放所有svg文件;在icons下创建index.js。

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component

// register globally
Vue.component('svg-icon', SvgIcon)

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

在main.js中引入

import '@/src/icons'

在组件中使用

//在代码中使用
<svg-icon icon-class="password" />

参考文章