vue-cli3使用svg图标的详细步骤
生活随笔
收集整理的這篇文章主要介紹了
vue-cli3使用svg图标的详细步骤
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.安裝依賴
npm install svg-sprite-loader -D2.在vue.config.js里添加配置
module.exports={chainWebpack: config => {const svgRule = config.module.rule("svg"); svgRule.uses.clear();svgRule.use("svg-sprite-loader").loader("svg-sprite-loader").options({symbolId: "icon-[name]"});}, }3.在src下創建文件夾svgIcon,并在該文件夾下創建index.vue,index.js和svg文件夾
4. index.vue的內容如下
<template> <svg :class="svgClass" aria-hidden="true"><use :xlink:href="iconName" /></svg> </template> <script> export default {name:'svgIcon',props:{data_iconName:{type:String,required:true},className:{type:String,default:''}},computed:{svgClass(){ //svg 的classif(this.className){return `svg-icon ${this.className}`;}else{return 'svg-icon'}},iconName(){ //svg xlink-href 指向的文件名return `#icon-${this.data_iconName}`;}} } </script> <style scoped>.svg-icon{width: 1em;height: 1em;vertical-align: -0.15em;fill: currentColor;overflow: hidden; } </style>5. index.js的內容如下
import Vue from "vue" import svgIcon from "./index.vue"Vue.component('svg-icon',svgIcon) //掛載全局組件 //下面這個是導入svgIcon/svg下的所有svg文件 const requireAll = requireContext => requireContext.keys().map(requireContext)const req = require.context('./svg', false, /.svg$/) /* 第一個參數是:'./svg' => 需要檢索的目錄, 第二個參數是:false => 是否檢索子目錄,第三個參數是: /.svg$/ => 匹配文件的正則 */ requireAll(req);6.將 index.js導入到main.js中
7.使用,作為測試,我們先從阿里字體圖標下載一個svg文件,放到svg文件夾下,如下圖
(注:可以直接下載svg文件,改名為fullscreen.svg;也可以先創建fullscreen.svg文件,然后在阿里字體復制svg代碼黏貼進去,效果是一樣的)
然后我們再home.vue里使用
<template><div class="home"><svg-icon data_iconName="fullscreen" className="fullscreen_icon" /></div> </template><script> export default {name: 'Home', } </script>
上面截圖中的“fullscreen”對應的就是svg文件夾下的fullscreen.svg文件;“fullscreen_icon”就是添加的class,便于修改圖標的大小
8.效果截圖
總結
以上是生活随笔為你收集整理的vue-cli3使用svg图标的详细步骤的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 100+ 值得收藏的 Web 开发资源
- 下一篇: vue-cli 4.x 配置 htmlW