vue中引入.svg圖標

前言

更多內容,請訪問個人 我的博客vue


建立SvgIcon組件

components 文件夾下新建 SvgIcon 文件夾,並在 SvgIcon 文件夾下新建 index.vue 文件,內容以下:webpack

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

<script>
export default {
  name: 'svg-icon',
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String
    }
  },
  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>
複製代碼

建立icons文件夾

src 文件夾下新建 icons 文件夾,並在 icons 文件夾下新建 svg 文件夾和 index.js 文件。 svg 文件夾中用來存放各類擴展的.svg圖標。 index.js 文件內容以下:web

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg組件

// 註冊到全局
Vue.component('svg-icon', SvgIcon)

const requireAll = requireContext => requireContext.keys().map(requireContext)
// eslint-disable-next-line
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)
複製代碼

在main.js中引入

import './icons'
複製代碼

下載插件

在項目的目錄下,執行命令:npm

npm i svg-sprite-loader --save
複製代碼

配置

build/webpack.base.conf.js 文件中,新增:bash

{
        test: /\.svg$/,
        loader: 'svg-sprite-loader',
        include: [resolve('src/icons')],
        options: {
          symbolId: 'icon-[name]'
        }
    }
    
    和
    
    exclude: [resolve('src/icons')],
複製代碼

添加後,以下代碼所示:svg

module: {
    rules: [
      ...(config.dev.useEslint ? [createLintingRule()] : []),
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/icons')],
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.svg$/,
        loader: 'svg-sprite-loader',
        include: [resolve('src/icons')],
        options: {
          symbolId: 'icon-[name]'
        }
      }
    ]
  },
複製代碼

使用

<svg-icon icon-class="user" />
複製代碼
相關文章
相關標籤/搜索