vite+vue3+vant使用svg图标

做项目时用到了iconfont的几个svg,不晓得咋搞上去,用的van-image和image标签效果都不理想,最后从网上找到了方法,记录下

首先封装一个SvgIcon组件

在components文件夹下新建一个SvgIcon.vue文件

<template>
    <svg aria-hidden="true" class="svg-icon">
        <use :xlink:href="symbolId" :fill="color" />
    </svg>
</template>

<script >
import { defineComponent, computed } from 'vue'

export default defineComponent({
    name: 'SvgIcon',
    props: {
        // 使用的svg图标名称,也就是svg文件名
        name: {
            type: String,
            required: true,
        },
        prefix: {
            type: String,
            default: 'icon',
        },
        color: {
            type: String,
            default: '#333',
        }
    },
    setup(props) {
        const symbolId = computed(() => `#${props.prefix}-${props.name}`)
        return { symbolId }
    },
})
</script>
<style scope>
.svg-icon {
    width: 50px;
    height: 50px;
    color: #333;
    fill: currentColor;
}
</style>

在使用的地方使用该组件,(用的vant的宫格组件)

<!--    宫格-->
    <div class="grid">
        <van-grid>
            <van-grid-item v-for="item in gridData" :key="item.title">
                <SvgIcon class="icon" :name="item.imgName" />
                {{ item.title }}
            </van-grid-item>
        </van-grid>
    </div>
const gridData = reactive([
    {
        title: '道破',
        imgName: 'daopo' // 名字对应文件名
    },
    {
        title: '赵飞燕',
        imgName: 'feiyan'
    },
    {
        title: '杨贵妃',
        imgName: 'guifei'
    },
    {
        title: '李清照',
        imgName: 'qingzhao'
    },
    {
        title: '武则天',
        imgName: 'wuzetian'
    },
    {
        title: '夏侯',
        imgName: 'xiahou'
    },
    {
        title: '敬爱',
        imgName: 'jingai'
    },
    {
        title: '赵毅',
        imgName: 'zhaoyi'
    }
])

 

 去main.js里注册一下组件

import SvgIcon from "@/components/SvgIcon.vue";

createApp(App).use().component('SvgIcon', SvgIcon).mount('#app')

再打开vite.config.js进行配置

import { resolve } from 'path'

const pathResolve = (pathStr) => {
  return resolve(__dirname, pathStr)
}

export default defineConfig({
    plugins: [
      vue(),
      createSvgIconsPlugin({
        iconDirs: [pathResolve('./src/assets/grid')], // svg的文件路径
        // 指定symbolId格式(这里的配置与6.2步骤中的引入svg组件的name配置项写法有关)
        symbolId: 'icon-[dir]-[name]',
    })
  ],
})

 完成后重新跑一下项目,svg图就出来了

 

posted @ 2023-02-02 15:31  幻影之舞  阅读(1777)  评论(0)    收藏  举报