Vue中使用SVG-ICON的配置方法

2024-03-01 0 556

在Vue中使用svg-icon,可以按如下配置即可。

1、src/components/SvgIcon目录下创建index.vue,代码如下:

<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>

2、src/assets/icons/下创建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)

3、src/assets/icons/svg目录下,放置用到的svg图片文件,如图中user.svg

4、main.js文件中增加对icons的引用,代码如下:

import \’./assets/icons\’

5、build目录中的webpack.base.conf.js的module.rules节点中增加如下代码:

{
test: /\\.svg$/,
loader: \’svg-sprite-loader\’,
include: [resolve(\’src/assets/icons\’)],
options: {
symbolId: \’icon-[name]\’
}
},
{
test: /\\.(png|jpe?g|gif|svg)(\\?.*)?$/,
loader: \’url-loader\’,
exclude: [resolve(\’src/assets/icons\’)],
options: {
limit: 10000,
name: utils.assetsPath(\’img/[name].[hash:7].[ext]\’)
}
},

6、config目录中的index.js的build节点中增加如下代码:

chainWebpack(config) {
// set svg-sprite-loader
config.module
rule(\’svg\’)
.exclude.add(resolve(\’src/assets/icons\’))
.end()
config.module
.rule(\’icons\’)
.test(/\\.svg$/)
.include.add(resolve(\’src/assets/icons\’))
.end()
.use(\’svg-sprite-loader\’)
.loader(\’svg-sprite-loader\’)
.options({
symbolId: \’icon-[name]\’
})
.end()
}

注:上述一步有些项目是用vue.config.js文件配置的,具体看具体配置。

7、执行下列命令安装 svg-sprite-loader 插件

npm install svg-sprite-loader –save-dev

8、代码中如何引用 svg 图标

<svg-icon icon-class=\”user\”></svg-icon>

到此这篇关于Vue中使用SVG-ICON的文章就介绍到这了,更多相关Vue使用SVG-ICON内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持悠久资源网!

您可能感兴趣的文章:

  • vue3+vite使用vite-plugin-svg-icons插件显示本地svg图标的方法
  • vue中使用svg-icon遇到的坑及解决
  • Vue封装svg-icon组件使用教程

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 JavaScript Vue中使用SVG-ICON的配置方法 https://www.u-9.cn/biancheng/javascript/182325.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务