vue中使用svg

在使用vue开发项目时,会遇到很多使用图标的场景。以使用阿里图标为例,假如你的项目中图标很固定,以后都不会变了,那么随便选择哪种方式的图标都可以。但是如果项目中图标会变,时不时的变个图标或者新增、减少一个图标,比较灵活的场景下使用svg会比较方便一些。

1、安装包

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

2、项目中使用的是vue-cli2手脚架的话,配置如下:

在build文件夹下找到webpack.bae.conf.js,

复制代码
module: {
    rules: [
         test: '/\.svg$/',
         include: [reslove('src/icon')],
         loader: ''svg-sprite-loader,
         options: {
              symboId: 'icon-[name]'       
        }          
    ]
复制代码

然后在找到如下代码,加上这一行 'exclude: [resolve('src/icons')],'

复制代码
{
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/icons')],
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
},
复制代码

使用cli3配置如下:

在新建的vue.config.js中,添加以下代码

复制代码
const path = require('path')
function resolve(dir) {
    return path.join(__dirname, dir)
}
module.exports = {
    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()
    }
}
复制代码

 3、在src目录下新建文件夹icons,把所有svg文件放进去,然后再新建index.js文件,获取icons目录下的所有svg文件

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

Vue.component('svg-icon', SvgIcon)

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

4、在3步骤,引入了SvgIcon组件,这个需要自己手写代码如下

复制代码
<template>
  <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
      <use :href="iconName" />
  </svg>
</template>

<script>
export default {
  name: 'SvgIcon',
  props:{
      iconClass:{
          type: String,
          require: 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>
复制代码

5、在main.js引入

//全局使用svg
import './icons'

6、使用

<svg-icon :iconName='location' />

 

posted @   朝思暮想的虫  阅读(1011)  评论(1编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示