vue項目使用阿里雲svg
先上一個目錄結構:
第一步:下載svg-sprite-loader
yarn add svg-sprite-loader -D
第二步:配置vue.config.js
1 const path = require("path"); 2 function resolve(dir) { 3 return path.join(__dirname, dir); 4 } 5 module.exports = { 6 lintOnSave: false, 7 transpileDependencies: ["vuetify"], 8 chainWebpack(config) { 9 // set svg-sprite-loader 10 // 第一步:讓其他svg loader不要對src/assets/imgs/svgs進行操作 11 config.module 12 .rule("svg") 13 .exclude.add(resolve("src/assets/imgs/svgs")) 14 .end(); 15 // 第二步:使用svg-sprite-loader 對 src/assets/imgs/svgs下的svg進行操作 16 config.module 17 .rule("icons") 18 .test(/\.svg$/) 19 .include.add(resolve("src/assets/imgs/svgs")) 20 .end() 21 .use("svg-sprite-loader") 22 .loader("svg-sprite-loader") 23 //定義規則 使用時 <svg class="icon"> <use xlink:href="#icon-svg文件名"></use> </svg> 24 .options({ 25 symbolId: "icon-[name]" 26 }) 27 .end(); 28 } 29 };
imgs/index.js:導入項目中用到的或者沒有用到的svg 一股腦全部導入
1 // 默認導入所有src文件夾下的icons文件(自動導入,不需手動一個個導入) 2 import Vue from "vue"; 3 import SvgIcon from "@/components/icon";//寫了組件在打開 用於注冊組件 4 5 Vue.component("svg-icon", SvgIcon);//寫了組件在打開 用於注冊組件 6 7 const requireAll = requireContext => requireContext.keys().map(requireContext); 8 const req = require.context("./svgs", false, /.svg$/); 9 requireAll(req);
main.js引入:
import "@/assets/imgs/index.js";
第三步:在頁面中使用
1 <template> 2 <div class="hello"> 3 <p>vue+svg-原生寫法 注意:eye是svg的文件名稱:eye.svg</p> 4 <svg class="icon"> 5 <use xlink:href="#icon-eye"></use> 6 </svg> 7 <p>vue+svg-組件寫法-下一步再講</p> 8 </div> 9 </template> 10 11 <script> 12 export default { 13 name: "HelloWorld", 14 props: { 15 msg: String 16 } 17 }; 18 </script> 19 <style scoped lang="scss"> 20 .icon { 21 width: 100px; 22 height: 100px; 23 vertical-align: -0.15em; 24 fill: currentColor; 25 overflow: hidden; 26 } 27 </style>
效果如下
組件寫法:簡單便捷
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 default: "" 18 } 19 }, 20 computed: { 21 iconName() { 22 return `#icon-${this.iconClass}`; 23 }, 24 svgClass() { 25 if (this.className) { 26 return "svg-icon" + this.className; 27 } else { 28 return "svg-icon"; 29 } 30 } 31 } 32 }; 33 </script> 34 35 <style scoped> 36 .svg-icon { 37 width: 1em; 38 height: 1em; 39 vertical-align: -0.15em; 40 fill: currentColor; 41 overflow: hidden; 42 } 43 </style>
1 <div class="hello"> 2 <p>vue+svg-原生寫法</p> 3 <svg class="icon"> 4 <use xlink:href="#icon-search"></use> 5 </svg> 6 <p>vue+svg-組件寫法-下一步再講</p> 7 <svg-icon icon-class="search"></svg-icon> 8 </div>