vue2中使用svg图标

1.安装插件

cnpm install -S svg-sprite-loader

2.封装svg组件

        src/SvgIcon/index.vue






3. 注册为全局组件及配置(js文件)

        src/assets/icons/index.js


import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon/index.vue'// 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)

 4.在main.js引入

import '@/assets/icons/index'

5.webpack.config.js或vue.config.js中配置 

const path = require('path')

function resolve (dir) {
  return path.join(__dirname, dir)
}

module.exports = defineConfig({
  transpileDependencies: true,
  // svg
  chainWebpack: config => {
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))
      .end()

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

6.使用svg

 

 

你可能感兴趣的:(前端)