vue項目中進行svg組件封裝及配置方法步驟
最近剛入新的公司,拿到項目之后,發(fā)現一個有趣的事情就是標題的icon是用svg來弄的,這篇文章徹底弄清楚怎么使用
1.創(chuàng)建vue項目(通過cli來搭建腳手架,該測試項目是用vue cli4進行配置的)
2.創(chuàng)建一個自定義組件
具體代碼如下:
<template> <svg :class="svgClass" aria-hidden="true" v-on="$listeners"> <use :xlink:href="iconName" rel="external nofollow" /> </svg> </template> <script> export default { name: "SvgIcon", props: { iconClass: { type: String, required: true, }, className: { type: String, default: "", }, }, 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>
3.在根目錄創(chuàng)建icons,新建一個index.js(等會全局引入),和新建一個svg目錄,專門放svg圖片(至于怎么下載svg, 阿里的iconfont就可以下載,自行百度)
index.js的具體代碼如下:
import Vue from 'vue' import SvgIcon from '@/components/svgIcon'// svg組件 // register globally Vue.component('svg-icon', SvgIcon) const req = require.context('./svg', false, /\.svg$/) const requireAll = requireContext => requireContext.keys().map(requireContext) requireAll(req)
4.全局引入main.js進行引入
5.此時項目還需要進行配置vue.config.js(不然無法顯示出來)
const path = require('path') module.exports = { chainWebpack: config => { const svgRule = config.module.rule('svg') svgRule.uses.clear() svgRule .test(/\.svg$/) .include.add(path.resolve(__dirname, './src/icons')).end() .use('svg-sprite-loader') .loader('svg-sprite-loader') .options({ symbolId: 'icon-[name]' }) const fileRule = config.module.rule('file') fileRule.uses.clear() fileRule .test(/\.svg$/) .exclude.add(path.resolve(__dirname, './src/icons')) .end() .use('file-loader') .loader('file-loader') } }
這樣就完成了;
6.項目中進行使用組件
這里我用的是函數式組件進行引入,也可以通過正常的組件使用方法引入
<script> export default { functional: true, props: { level: { type: Number, required: true, }, }, render: function (h, context) { console.log(context); let vnodes = []; let { level } = context.props; // vnodes.push(<i class="el-icon-edit" style="width:19px"></i>); vnodes.push(<svg-icon icon-class="date"></svg-icon>); vnodes.push(<span class="span">{level}</span>); return vnodes; }, }; </script> <style scoped> .span { font-size: 50px; } </style>
注意:icon-class的值直接是svg的文件名。
到此這篇關于vue項目中進行svg組件封裝及配置方法步驟的文章就介紹到這了,更多相關vue svg組件封裝配置內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于vue-admin-template模板連接后端改造登錄功能
這篇文章主要介紹了關于vue-admin-template模板連接后端改造登錄功能,登陸方法根據賬號密碼查出用戶信息,根據用戶id與name生成token并返回,userinfo則是對token進行獲取,在查出對應值進行返回,感興趣的朋友一起看看吧2022-05-05