vue中使用svg并设置大小

2023-06-13,,

1、安装依赖

npm install --save-dev svg-sprite-loader

2、 新建svg资源文件夹     src/assets/svg

将svg资源放入此目录,接下来会在配置文件中该路径

3、vue-cli 脚手架项目3.x 以上配置  vue.config.js

 1 const path = require('path')
2 module.exports = {
3 chainWebpack: config => {
4 // svg rule loader
5 const svgRule = config.module.rule('svg') // 找到svg-loader
6 svgRule.uses.clear() // 清除已有的loader, 如果不这样做会添加在此loader之后
7 svgRule.exclude.add(/node_modules/) // 正则匹配排除node_modules目录
8 svgRule // 添加svg新的loader处理
9 .test(/\.svg$/)
10 .use('svg-sprite-loader')
11 .loader('svg-sprite-loader')
12 .options({
13 symbolId: 'icon-[name]',
14 })
15 // 修改images loader 添加svg处理
16 const imagesRule = config.module.rule('images')
17 imagesRule.exclude.add(path.resolve(__dirname, 'src/assets/svg')) //注意这个路径,为svg资源文件的路径
18 config.module
19 .rule('images')
20 .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
21 }
22 }

4、创建组件  SvgIcon.vue  ( src/compoments/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 } else {
27 return 'svg-icon'
28 }
29 }
30 }
31 }
32 </script>
33
34 <style scoped>
39 </style>

5、组件注册(全局)  (src/utils/iconsSvg.js)

 1 import Vue from 'vue'
2 import SvgIcon from '@/components/SvgIcon' //引入第四步的组件
3
4 // 全局注册组件
5 Vue.component('svg-icon', SvgIcon)
6 // 定义一个加载目录的函数
7 const requireAll = requireContext => requireContext.keys().map(requireContext)
8 const req = require.context('@/assets/svg', false, /\.svg$/) //为svg资源文件的路径
 9 // 加载目录下的所有 svg 文件 10 requireAll(req)

6、引入组件  main.js

import './utils/iconsSvg'

7、使用svg组件
iconClass: svg文件的文件名
className: svg图标的样式类名

 1 <template>
2 <div>
3 <p>小明同学的大头贴</p>
4 <svg-icon iconClass="boy" className="boy"></svg-icon>
5 </div>
6 </template>
7
8 <style scoped>
9 .boy {
10 width: 200px;
11 height: 200px;
12 }
13 </style>

vue中使用svg并设置大小的相关教程结束。

《vue中使用svg并设置大小.doc》

下载本文的Word格式文档,以方便收藏与打印。