VUE定义一个svg组件并使用

1.在components文件下 新建 Svgicon.vue文件,存放组件内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" />
  </svg>
</template><br>
<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>

2.在src/assets文件夹下新建 icons文件夹,icons 新建子文件夹svg。里面存放下载的.svg文件,svg文件夹同级新建index,js文件  

index.js:

1
2
3
4
5
6
7
8
9
10
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon.vue'  //svg组件
 
Vue.component('svg-icon', SvgIcon) //注册组件 (组件名称,配置目标组件)
 
 
// 正则匹配引入所有.svg文件模块
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)

3.main.js文件中引入index.js文件

1
import '@/assets/icons/index.js'

4.vue.config.js中配置相关规则  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const path = require('path')
 
module.exports = {
  devServer: {
    port: 9000,
    open: true
  },
 
  chainWebpack: config => {
    const svgRule = config.module.rule('svg')
    // 清除已有的所有svg loader
    svgRule.uses.clear()
    svgRule
      .test(/\.svg$/)
      .include.add(path.resolve(__dirname, './src/assets/icons/svg'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
  }
}

5.项目中使用 svg-icon组件  

1
<svg-icon icon-class="setting" class="icon-setting"></svg-icon>  //icon-class="setting" svg文件名称

SVG中有四个主要的元素用于在文档中定义、结构化和引用SVG代码:<g>, <defs>, <use> 和 <symbol>。

<g>元素(“group”的简写),用于给逻辑上相联系的图形元素分组。
<defs>元素用来定义你之后要重用的元素。
<symbol>元素结合了<defs>和<g>元素的优点,将定义模板的元素组合在一起,以便之后在文档中的其他位置引用。比其它两个元素有一个非常重要的优点:它接受一个viewBox属性,可以让它在任何视窗中自适应大小缩放渲染。
<use>元素用于引用文档中其它位置定义的元素。你可以重用已有的元素,类似于图形编辑器中的复制粘贴功能。它可以重用单个元素,也可以重用一组用<g>、<defs>或<symbol>定义的元素。
要使用一个元素,你需要通过一个标识对该元素进行引用——一个ID,即use中的xlink:href属性,以及用来给该元素定位的x和y属性。你可以给use元素应用样式,这些样式也会级联应用到use元素的内容中去。

  

posted on   不酷也要写代码  阅读(490)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战

导航

< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
点击右上角即可分享
微信分享提示