vue3 + vite项目使用SVG图标

我们在开发一个项目时常会用到一些图标,有些图标在有限的图标库中却是没有,因此少数的图标需要我们去网上查找,或是自定义一些专用的图标。一般很少有图标库满足现实的项目开发,这时将推荐使用 iconify 这个图标库,几乎包含我们常见全部的图标,使用也非常简单。废话不多说咱们开始真刀实战。

引入vite插件

  • unplugin-icons
  • unplugin-vue-components
  • vite-plugin-svg-icons
  • @iconify/json
  • @iconify/vue
# npm

npm i -D @iconify/json @iconify/vue unplugin-icons vite-plugin-svg-icons unplugin-vue-components

#yarn

yarn add -D @iconify/json @iconify/vue unplugin-icons vite-plugin-svg-icons unplugin-vue-components

#pnpm

pnpm add -D @iconify/json @iconify/vue unplugin-icons vite-plugin-svg-icons unplugin-vue-components

使用方式

第一种:unplugin-icons

配置vite插件:

 // 配置图标- unplugin-icons
Icons({
    compiler: "vue3",
    customCollections: {
       ["local"]: FileSystemIconLoader(LOCAL_PATH, (svg: string) =>
               svg.replace(/^<svg\s/, '<svg width="1em" height="1em" '))
       },
    scale: 1,
    autoInstall: true,
    defaultClass: "inline-block"
}),
// 配置unplugin-vue-components
Components({
    resolvers: [
        IconsResolver({
           prefix: "icon",
           customCollections: COLLECTION_NAME,
        }),
    ],
}),
  1. 使用iconify图标作为载体显示:
<!--  使用图标  -->
<icon-ep-bicycle style="font-size: 30px;color: #0C0C0C;background-color: #efafaf"></icon-ep-bicycle>

效果:

图标解释:

icon 为我们自定义的前缀

ep-bicycle 为图标的名字,可以去iconify查询,将冒号 :更换横杠 - 。

        2. 使用本地svg图标作为载体显示

下载svg图标文件,放在项目的 src/assets/icons/svg 目录下

<!--  使用图标  -->
<icon-local-acrobat class="icons"></icon-local-acrobat>
<icon-local-control-center class="icons"></icon-local-control-center>
<icon-local-setting class="icons"></icon-local-setting>

效果:

图标的样式部分可自行调整,演示的样式是我自定义的

图标解释:

icon-local-acrobat

icon 为我们自定义的前缀

local 为我们自定义的集合容器名,在配置vite时指定的

acrobat 为图标文件的名字

第二种:vite-plugin-svg-icons

配置vite插件

// 配置图标- vite-plugin-svg-icons
createSvgIconsPlugin({
    // 指定需要缓存的图标文件夹
    iconDirs: [LOCAL_PATH],
    // 指定symbolId格式
    symbolId: `icon-[dir]-[name]`,
    inject: "body-last",
    customDomId: "__SVG_ICON_LOCAL__",
})

在main.ts中引入样式

import "virtual:svg-icons-register";

自定义SvgIcon组件方便图标的使用,这里我使用的是jsx的形式定义的组件,用vue定义的组件可以自行参照下面的形式写即可。

import type {CSSProperties, PropType} from "vue";
import {computed, defineComponent} from "vue";
import {Icon} from "@iconify/vue";

// horizontal: 水平翻转 ,vertical:垂直翻转
type FlipType = "horizontal" | "vertical";
// 数字代表旋转角度  0° 90° 180° 270°
type RotateType = 0 | 1 | 2 | 3;

/**
 * SvgIcon 组件
 * @date 2023/9/26
 */
export default defineComponent({
    name: "SvgIcon",
    props: {
        // 图标名字
        icon: {
            type: String,
            required: true,
            default: "",
        },
        // 是否为本地 svg 图标
        isLocal: {
            type: Boolean,
            default: false,
        },
        // 图标大小
        size: {
            type: [Number, String],
            default: 14,
        },
        // 旋转角度
        rotate: {
            type: Number as PropType<RotateType>,
            default: 0,
        },
        // 图标翻转(水平翻转、垂直翻转)
        flip: String as PropType<FlipType>,
        // 图标旋转动画效果
        spin: {
            type: Boolean,
            default: false,
        },
        // 单独图标样式
        iconStyle: Object as PropType<CSSProperties>,
        // 图标颜色
        color: String,
        // 点击图标触发事件
        onClick: Function as PropType<(e: MouseEvent) => void>,
    },
    setup(props, {attrs}) {
        const bindAttrs = computed<{ class: string; style: string }>(() => ({
            class: (attrs.class as string) || "",
            style: (attrs.style as string) || "",
        }));

        const symbolId = () => `#icon-${props.icon}`;

        const rotate = [0, 90, 180, 270];

        const localIconStyle = {
            width: "1em",
            height: "1em",
            lineHeight: "1em",
            fontSize: `${`${props.size}`.replace("px", "")}px`,
            animation: props.spin ? "circle 3s infinite linear" : "",
            transform: (() => {
                const scale = props.flip
                    ? props.flip == "vertical"
                        ? "scaleY(-1)"
                        : props.flip == "horizontal"
                            ? "scaleX(-1)"
                            : ""
                    : "";
                return `rotate(${rotate[props.rotate]}deg) ${scale}`;
            })(),
        };

        const iconStyles = {outline: "none", animation: props.spin ? "circle 3s infinite linear" : ""};
        return () => (
            <b
                onClick={e => {
                    props.onClick?.(e);
                }}
                class={["inline-block", bindAttrs.value.class, props.onClick ? "cursor-pointer" : ""]}
                style={bindAttrs.value.style}
            >
                {props.isLocal ? (
                    <svg aria-hidden="true"
                         style={props.iconStyle ? Object.assign(localIconStyle, props.iconStyle) : localIconStyle}>
                        <use xlinkHref={symbolId()} fill="currentColor"/>
                    </svg>
                ) : (
                    <Icon
                        icon={props.icon}
                        width={props.size}
                        height={props.size}
                        rotate={props.rotate}
                        flip={props.flip}
                        color={props.color}
                        style={props.iconStyle ? Object.assign(iconStyles, props.iconStyle) : iconStyles}
                    />
                )}
            </b>
        );
    },
});

使用iconify图标

<!--  使用图标  -->
<SvgIcon icon="ep:avatar" size="50" color="#000"></SvgIcon>

使用本地图标

<!--  使用图标  -->
<SvgIcon icon="setting" size="50" is-local class="icons"></SvgIcon>

区别是使用本地svg图标时需要 isLocal 设置为true,其他的属性可自行摸索,在组件中也有相应的代码注释

完整代码

vite配置:

import {fileURLToPath, URL} from 'node:url'

import {defineConfig} from 'vite'
import path from "path";
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import Icons from "unplugin-icons/vite";
import {FileSystemIconLoader} from "unplugin-icons/loaders";
import {createSvgIconsPlugin} from "vite-plugin-svg-icons";
import Components from "unplugin-vue-components/vite";
import IconsResolver from 'unplugin-icons/resolver';

/**
 * 获取项目根路径
 * @descrition 末尾不带斜杠
 */
export function getRootPath() {
    return path.resolve(process.cwd());
}

/**
 * 获取项目src路径
 * @param srcName - src目录名称(默认: "src")
 * @descrition 末尾不带斜杠
 */
export function getSrcPath(srcName = "src") {
    const rootPath = getRootPath();
    return `${rootPath}/${srcName}`;
}

const LOCAL_PATH = `${getSrcPath()}/assets/icons/svg`
const COLLECTION_NAME = "local"

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue(),
        vueJsx(),
        // 配置unplugin-vue-components
        Components({
            resolvers: [
                IconsResolver({
                    prefix: "icon",
                    customCollections: COLLECTION_NAME,
                }),
            ],
        }),
        // 配置图标- unplugin-icons
        Icons({
            compiler: "vue3",
            customCollections: {
                [COLLECTION_NAME]: FileSystemIconLoader(LOCAL_PATH, (svg: string) =>
                    svg.replace(/^<svg\s/, '<svg width="1em" height="1em" '),
                ),
            },
            scale: 1,
            autoInstall: true,
            defaultClass: "inline-block",
        }),
        // 配置图标- vite-plugin-svg-icons
        createSvgIconsPlugin({
            // 指定需要缓存的图标文件夹
            iconDirs: [LOCAL_PATH],
            // 指定symbolId格式
            symbolId: `icon-[dir]-[name]`,
            inject: "body-last",
            customDomId: "__SVG_ICON_LOCAL__",
        })
    ],
    resolve: {
        alias: {
            '@':
                fileURLToPath(new URL('./src', import.meta.url))
        }
    }
})

SvgIcon组件:

import type {CSSProperties, PropType} from "vue";
import {computed, defineComponent} from "vue";
import {Icon} from "@iconify/vue";

// horizontal: 水平翻转 ,vertical:垂直翻转
type FlipType = "horizontal" | "vertical";
// 数字代表旋转角度  0° 90° 180° 270°
type RotateType = 0 | 1 | 2 | 3;

/**
 * SvgIcon 组件
 * @date 2023/9/26
 */
export default defineComponent({
    name: "SvgIcon",
    props: {
        // 图标名字
        icon: {
            type: String,
            required: true,
            default: "",
        },
        // 是否为本地 svg 图标
        isLocal: {
            type: Boolean,
            default: false,
        },
        // 图标大小
        size: {
            type: [Number, String],
            default: 14,
        },
        // 旋转角度
        rotate: {
            type: Number as PropType<RotateType>,
            default: 0,
        },
        // 图标翻转(水平翻转、垂直翻转)
        flip: String as PropType<FlipType>,
        // 图标旋转动画效果
        spin: {
            type: Boolean,
            default: false,
        },
        // 单独图标样式
        iconStyle: Object as PropType<CSSProperties>,
        // 图标颜色
        color: {
            type: String,
            default: "#000",
        },
        // 点击图标触发事件
        onClick: Function as PropType<(e: MouseEvent) => void>,
    },
    setup(props, {attrs}) {
        const bindAttrs = computed<{ class: string; style: string }>(() => ({
            class: (attrs.class as string) || "",
            style: (attrs.style as string) || "",
        }));

        const symbolId = () => `#icon-${props.icon}`;

        const rotate = [0, 90, 180, 270];

        const localIconStyle = {
            width: "1em",
            height: "1em",
            lineHeight: "1em",
            fontSize: `${`${props.size}`.replace("px", "")}px`,
            animation: props.spin ? "circle 3s infinite linear" : "",
            transform: (() => {
                const scale = props.flip
                    ? props.flip == "vertical"
                        ? "scaleY(-1)"
                        : props.flip == "horizontal"
                            ? "scaleX(-1)"
                            : ""
                    : "";
                return `rotate(${rotate[props.rotate]}deg) ${scale}`;
            })(),
        };

        const iconStyles = {outline: "none", animation: props.spin ? "circle 3s infinite linear" : ""};
        return () => (
            <b
                onClick={e => {
                    props.onClick?.(e);
                }}
                class={["inline-block", bindAttrs.value.class, props.onClick ? "cursor-pointer" : ""]}
                style={bindAttrs.value.style}
            >
                {props.isLocal ? (
                    <svg aria-hidden="true"
                         style={props.iconStyle ? Object.assign(localIconStyle, props.iconStyle) : localIconStyle}>
                        <use xlinkHref={symbolId()} fill="currentColor"/>
                    </svg>
                ) : (
                    <Icon
                        icon={props.icon}
                        width={props.size}
                        height={props.size}
                        rotate={props.rotate}
                        flip={props.flip}
                        color={props.color}
                        style={props.iconStyle ? Object.assign(iconStyles, props.iconStyle) : iconStyles}
                    />
                )}
            </b>
        );
    },
});

main.ts 引入

import "virtual:svg-icons-register";

使用:

<script setup lang="ts">
import SvgIcon from "@/components/SvgIcon";
</script>

<template>
  <main style="display: flex;flex-direction: column">
    <!--  使用图标  -->
    <icon-ep-bicycle class="icons"></icon-ep-bicycle>

    <!--  使用图标  -->
    <icon-local-acrobat class="icons"></icon-local-acrobat>
    <icon-local-control-center class="icons"></icon-local-control-center>
    <icon-local-setting class="icons"></icon-local-setting>


    <!--  使用图标  -->
    <SvgIcon icon="ep:avatar" size="50"></SvgIcon>

    <!--  使用图标  -->
    <SvgIcon icon="setting" size="50" is-local class="icons"></SvgIcon>
  </main>
</template>

<style scoped>
.icons {
  font-size: 30px;
  color: #0C0C0C;
  background-color: #efafaf;
  margin: 20px;
}
</style>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于 Vue3 和 Vite 的实现拖拽产生连线的代码示例: ```html <template> <div class="container"> <div class="box" v-for="(item, index) in boxes" :key="item.id" :style="{ top: item.top + 'px', left: item.left + 'px' }" @mousedown="mousedown(index)"> {{ item.name }} </div> <svg class="line-container"> <line v-for="(line, index) in lines" :key="index" :x1="line.x1" :y1="line.y1" :x2="line.x2" :y2="line.y2" /> </svg> </div> </template> <script> import { reactive, toRefs } from 'vue' export default { setup() { const state = reactive({ boxes: [ { id: 1, name: 'Box 1', top: 100, left: 100 }, { id: 2, name: 'Box 2', top: 200, left: 200 }, { id: 3, name: 'Box 3', top: 300, left: 300 }, ], lines: [], isDragging: false, currentBoxIndex: null, startX: null, startY: null, }) const mousedown = (index) => { state.isDragging = true state.currentBoxIndex = index state.startX = state.boxes[index].left state.startY = state.boxes[index].top } const mousemove = (event) => { if (state.isDragging) { const box = state.boxes[state.currentBoxIndex] box.left = state.startX + event.clientX - state.startX - box.width / 2 box.top = state.startY + event.clientY - state.startY - box.height / 2 } } const mouseup = () => { state.isDragging = false state.currentBoxIndex = null } const connectBoxes = () => { const lastBox = state.boxes[state.boxes.length - 1] const secondLastBox = state.boxes[state.boxes.length - 2] state.lines.push({ x1: secondLastBox.left + secondLastBox.width / 2, y1: secondLastBox.top + secondLastBox.height / 2, x2: lastBox.left + lastBox.width / 2, y2: lastBox.top + lastBox.height / 2, }) } return { ...toRefs(state), mousedown, mousemove, mouseup, connectBoxes, } }, mounted() { document.addEventListener('mousemove', this.mousemove) document.addEventListener('mouseup', this.mouseup) }, beforeUnmount() { document.removeEventListener('mousemove', this.mousemove) document.removeEventListener('mouseup', this.mouseup) }, } </script> <style> .container { position: relative; height: 500px; } .box { position: absolute; width: 100px; height: 100px; background-color: #ccc; text-align: center; line-height: 100px; user-select: none; cursor: move; } .line-container { position: absolute; width: 100%; height: 100%; pointer-events: none; } </style> ``` 代码中实现了一个简单的拖拽产生连线的功能,具体实现方式如下: 1. 在模板中使用 `v-for` 渲染出多个可拖拽的方块(`<div class="box">`)和一个 SVG 容器(`<svg class="line-container">`)来绘制连线; 2. 通过 `@mousedown` 监听鼠标按下事件,记录当前拖拽的方块的索引和起始位置; 3. 通过 `@mousemove` 监听鼠标移动事件,根据当前鼠标位置计算出方块的新位置; 4. 通过 `@mouseup` 监听鼠标抬起事件,清空当前拖拽状态; 5. 通过方法 `connectBoxes` 将最后两个方块连线。 需要注意的是,代码中通过 `reactive` 创建了一个响应式对象 `state`,并使用 `toRefs` 将其转换为响应式引用,以便在模板中使用。并且,在组件的 `mounted` 和 `beforeUnmount` 钩子中分别添加和移除了全局的鼠标移动和抬起事件监听器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值