svg组件封装

svg图标优点

文件体积小,能够被大量的压缩

图片可无限放大而不失真(矢量图的基本特征)

在视网膜显示屏上效果极佳

能够实现互动和滤镜效果

svg图标使用

1.安装相应的npm包:

yarn add svg-sprite-loader svgo --dev 

2.src文件夹下新建一个icons文件夹。里面存放svg格式的图标。

index.js实现组件全部注册。

复制代码
1 import Vue from 'vue';
2 import SvgIcon from '@/components/SvgIcon.vue'; // svg组件
3 
4 // register globally
5 Vue.component('svg-icon', SvgIcon);
6 
7 const requireAll = requireContext => requireContext.keys().map(requireContext);
8 const req = require.context('./svg', false, /\.svg$/);
9 requireAll(req);
复制代码

SvgIcon.vue组件:

复制代码
 1 <template>
 2     <svg :class="svgClass" aria-hidden="true">
 3         <use :xlink:href="iconName"></use>
 4     </svg>
 5 </template>
 6 
 7 <script>
 8 export default {
 9   name: 'svg-icon',
10   props: {
11     iconClass: {
12       type: String,
13       required: true
14     },
15     className: {
16       type: String
17     }
18   },
19   computed: {
20     iconName() {
21       return `#icon-${this.iconClass}`;
22     },
23     svgClass() {
24       if (this.className) {
25         return `svg-icon ${this.className}`;
26       }
27       return 'svg-icon';
28     }
29   }
30 };
31 </script>
32 
33 <style scoped>
34 .svg-icon {
35     width: 20px;
36     height: 20px;
37     vertical-align: -0.15em;
38     fill: currentColor;
39     overflow: hidden;
40 }
41 </style>
复制代码

3.在vue.config.js里set svg-sprite-loader

4.别忘了在main.js中引入:

复制代码
import Vue from 'vue';
import './icons';

import router from './router';
import store from './store';

import './assets/styles/index.scss';

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  template: '<router-view></router-view>',
}).$mount('#app');
复制代码

5.然后,就可以使用了

<el-form-item prop="username">
    <svg-icon icon-class="user" class="icon-svg" />
    <el-input placeholder="请输入邮箱" type="text" v-model="loginForm.username" />
</el-form-item>

 

posted @   鼓舞飞扬  阅读(883)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示