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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM