请演示用“class”属性批量命名路径,并在 Vue 项目中动态修改 fill 颜色。

解读

面试官真正想看的是三件事:

  1. 你是否熟悉 Inkscape 的“批量命名”技巧,而不是手工一条一条改 id;
  2. 你是否知道 SVG 的 class 与 CSS 变量/JS 的联动机制;
  3. 你是否能把设计师端的 SVG 与前端 Vue 代码无缝衔接,解决“设计改一版、前端重切一遍”的国内协作痛点。

因此,回答时要“设计端讲效率、前端讲规范、协作讲可持续”。

知识点

  1. Inkscape「对象属性」面板与「查找/替换」对话框:可一次性给多条路径写 class,避免 id 重复。
  2. SVG 1.1 class 属性:与 HTML 类似,支持多值空格分隔,可被 <style>、CSS 变量、Vue 动态 style 同时控制。
  3. CSS 变量穿透:Vue 中只需在父级写 --theme-color,子级 fill="var(--theme-color)" 即可响应式刷新,无需操作 DOM。
  4. 国内激光切割/印刷厂常要求“路径名规范 + 颜色映射表”,用 class 命名方便后端脚本一次性识别。

答案

(以下步骤可直接在面试白板口述,也可让面试官投影跟做)

一、Inkscape 端:30 秒批量加 class

  1. 打开示例文件,Shift+Ctrl+F 调出「查找/替换」→「对象」标签;
  2. 属性选“class”,值留空,点击「查找」→ 所有路径被选中;
  3. 右侧「对象属性」面板 → Class 输入框键入:logo-main theme-fill;
  4. 再次选中另一组装饰线,重复 2-3,写入:logo-accent theme-stroke;
  5. 文件 → 另存为「Plain SVG」,勾选“优化”→ 得到纯净 SVG。

二、Vue 端:10 行代码动态换色

npm i vite-plugin-svg-icons -D   # 任意 SVG 加载器均可

src/assets/logo.svg(Inkscape 导出后拷入)

<svg viewBox="0 0 200 200">
  <path class="logo-main theme-fill" d="…"/>
  <path class="logo-accent theme-stroke" d="…"/>
</svg>

App.vue

<template>
  <!-- CSS 变量一次性下发,子级自动刷新 -->
  <svg class="logo" :style="cssVars">
    <use href="@/assets/logo.svg#logo"></use>
  </svg>
  <input type="color" v-model="themeColor" />
</template>

<script setup>
import { ref, computed } from 'vue'
const themeColor = ref('#ff6600')
const cssVars = computed(() => ({
  '--theme-fill': themeColor.value,
  '--theme-stroke': themeColor.value
}))
</script>

<style scoped>
.logo >>> .theme-fill   { fill: var(--theme-fill); }
.logo >>> .theme-stroke { stroke: var(--theme-stroke); }
</style>

三、国内落地细节

  • 若需兼容老安卓, postcss-custom-properties 可自动降级;
  • 如果交付给 CNC 同事,class 命名直接对应“切割顺序表”,如 cut-outer、cut-inner,省去额外对照文档;
  • 设计走查时,UI 只需在 Inkscape 改色值再导出,前端零改动,符合国内“版本迭代快、人力紧张”的现状。

拓展思考

  1. 当路径数量 >1 000 时,Inkscape GUI 会卡顿,可改用「XML 编辑器」+ 正则批量替换,或写一行 inx 脚本自动给选中节点加 class;
  2. 如果项目要求“主题多色 + 暗色模式”,可把 class 拆成 semantic-token(如 primary、secondary),再用 TailwindCSS 的 theme() 函数映射,设计端与代码端共用一份 design token JSON;
  3. 对大型可视化大屏,SVG 节点过多导致 Vue 响应式开销增大,可降级为 CSS mask + background-image,把换色逻辑从“操作节点”转为“切换类名”,帧率可提升 30% 以上。