vue嵌入SVG

1、新建组件

<template>
    <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
        <use :xlink:href="iconName" />
    </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、新建一个文件夹用于存放svg
3、新建一个index.js用于读取svg

import Vue from 'vue'
import SvgIcon from '../components/custom/SvgIcon.vue'// svg组件

// register globally
Vue.component('svg-icon', SvgIcon)

//第一个参数是要遍历的目录,第二个参数指定是否遍历子目录,网络上其它地方一般都是false
const req = require.context('./svg', true, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

4、配置webpack读取规则
在vue.config.js中添加webpack的规则,如果没有这个文件则创建一个放在项目的根目录,因为不同人的配置文件不同,所以这里只放部分代码,以表示配置在什么地方
module.exports = {
chainWebpack: config => {
// 添加别名(src默认为@,不用再次添加)
config.resolve.alias
.set(’@pub’, resolve(‘public’)) // 设置public别名为@pub

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

}
5、在main.js文件中

import './icons'//放index.js的文件夹

new Vue({
    router,
    store,
    render: h => h(App)
}).$mount('#app')


6、使用SVG

<template>
    <div class="left">
        <svg-icon class="svg-pic" icon-class="项目"></svg-icon>
    </div>
</template>

<script>
export default {
    name: "ToolBar",
    data(){
        return {
        }
    }
}
</script>

<style scoped>
.svg-pic{
    color:red
}
</style>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员阿明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值