vue3+vite项目使用svg

1、文件目录

2、安装 svg-sprite-loader  npm install svg-sprite-loader

3、创建svgIcon.vue文件

<template>
  <div
    v-if="external"
    :style="styleExternalIcon"
    v-bind="$attrs"
    class="svg-external-icon svg-icon"
  />
  <!--  v-on="$listeners"-->
  <svg v-else :class="svgClass" v-bind="$attrs" aria-hidden="true">
    <use :href="iconName" />
  </svg>
</template>

<script setup>
  // doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usage
  import { isExternal } from '@/utils/validate';
  import { computed } from 'vue';

  const props = defineProps({
    iconClass: {
      type: String,
      required: false,
      default: 'non-existent',
    },
    className: {
      type: String,
      default: '',
    },
    customClass: {
      type: String,
      default: '',
    },
  });

  const external = computed(() => {
    return isExternal(props.iconClass);
  });
  const iconName = computed(() => {
    return `#icon-${props.iconClass}`;
  });
  const svgClass = computed(() => {
    if (props.className) {
      return 'svg-icon ' + props.className;
    }
    if (props.customClass) {
      return props.customClass;
    }
    return 'svg-icon';
  });
  const styleExternalIcon = computed(() => {
    return {
      mask: `url(${props.iconClass}) no-repeat 50% 50%`,
      '-webkit-mask': `url(${props.iconClass}) no-repeat 50% 50%`,
    };
  });
</script>

<style scoped>
  .svg-icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }

  .svg-external-icon {
    background-color: currentColor;
    mask-size: cover !important;
    display: inline-block;
  }
</style>

4、创建icons文件夹,存放svg文件

5、在main.js里面全局注入svg-icon组件

import { createApp } from "vue";
import App from "./App.vue";
​
import svgIcon from './icons/svgIcon.vue'
​
createApp(App)
    .component('svg-icon', svgIcon)
    .mount("#app");

6、在plugins文件夹创建svgBuilder.js

import { readFileSync, readdirSync } from 'fs';

let idPerfix = '';
const svgTitle = /<svg([^>+].*?)>/;
const clearHeightWidth = /(width|height)="([^>+].*?)"/g;
const hasViewBox = /(viewBox="[^>+].*?")/g;
const clearReturn = /(\r)|(\n)/g;

// 查找svg文件
function svgFind(e) {
  const arr = [];
  const dirents = readdirSync(e, { withFileTypes: true });
  for (const dirent of dirents) {
    if (dirent.isDirectory()) arr.push(...svgFind(e + dirent.name + '/'));
    else {
      const svg = readFileSync(e + dirent.name)
        .toString()
        .replace(clearReturn, '')
        .replace(svgTitle, ($1, $2) => {
          let width = 0,
            height = 0,
            content = $2.replace(clearHeightWidth, (s1, s2, s3) => {
              if (s2 === 'width') width = s3;
              else if (s2 === 'height') height = s3;
              return '';
            });
          if (!hasViewBox.test($2))
            content += `viewBox="0 0 ${width} ${height}"`;
          return `<symbol id="${idPerfix}-${dirent.name.replace(
            '.svg',
            ''
          )}" ${content}>`;
        })
        .replace('</svg>', '</symbol>');
      arr.push(svg);
    }
  }
  return arr;
}

// 生成svg
export const createSvg = (path, perfix = 'icon') => {
  if (path === '') return;
  idPerfix = perfix;
  const res = svgFind(path);
  return {
    name: 'svg-transform',
    transformIndexHtml(dom) {
      return dom.replace(
        '<body>',
        `<body><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">${res.join(
          ''
        )}</svg>`
      );
    },
  };
};

7、最后在vite.config.js修改配置

import { fileURLToPath, URL } from "node:url";
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
​
//这里会报svgIcon.ts不在tsconfig.config.json文件列表中,在tsconfig.config.json的include里加
//"./src/icons/svgIcon.ts"就行,不加对npm run dev没影响
import { createSvg } from './src/icons/svgIcon'
​
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), createSvg('./src/icons/svg/')],
  resolve: {
    alias: {
      "@": fileURLToPath(new URL("./src", import.meta.url)),
    },
  },
});

8、配置完毕,我们可以用以下方式导入自己的svg图片

<svg-icon icon-class="scene"/>

亲测有效!!!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个基于 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` 钩子中分别添加和移除了全局的鼠标移动和抬起事件监听器。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值