当前位置: 首页 > Skill >

Vue To Umijs

Vue To Umijs

Vue To Umijs

将 Vue2/3 项目迁移到基于 UmiJS (@umijs/max) 的 React:约定、限制、栈映射、语法示例(单个 SKILL.md)。适用于 .vue → Umi 项目。

0.1.0 2026.11.26 606
获取Skill文件查看使用说明
作 者:江辰 许可证: 更新时间:2026.11.26
本文目录展开

Vue → UmiJS + React migration

Goal: move a Vue codebase to UmiJS (@umijs/max) + React 18 + antd, with behavior parity and Umi’s routing, data flow, and folder conventions.

Document layout: rules and constraints first; Stack and Umi mapping next; Syntax examples last.

Scope

  • Source: Vue 2 / 3 (Options API, Composition API, SFC).
  • Target: Umi 4 + @umijs/max + React 18; function components and hooks; TypeScript for public APIs.
  • Default stack: antd; src/models + useModel; React Router v6 (via Umi); Less + *.module.less; pages as PageName/index.tsx + PageName/index.module.less.

Principles

  1. Parity first: routing, URL, guards, loading/errors, and UX before micro-optimizations.
  2. Single source of truth: no duplicate domain state across store and local state unless there is an explicit draft/edit buffer.
  3. Side-effect boundaries: useEffect (or Umi equivalents) for subscriptions and async with cleanup; cancel in-flight work with AbortController where needed.
  4. No Vue runtime: replace plugins, mixins, filters, and global buses with hooks, Umi models, and explicit modules.
  5. Closures and deps: dependency arrays reflect real deps; derive with render/useMemo, not effects for pure derivation.

API mapping (summary)

Area Direction
Page .vue PageName/index.tsx + index.module.less
Child .vue Foo.tsx + Foo.module.less (same folder, matching basename)
Component API defineComponent → function Name(props: NameProps); emit → onXxx
ref / reactive / computed / watch useState / useRef, useReducer, useMemo, useEffect (deps + cleanup)
Vue Router Umi config / routes; useNavigate, useParams, etc. — see Routing and data below
Pinia / Vuex src/models + useModel by domain; prefer useRequest for local fetch/cache
Element UI / Element Plus Map to antd with matching interaction and validation semantics

Constraints

  1. One router tree: use Umi nested routes/layouts; do not add a standalone BrowserRouter beside Umi; avoid full-page navigations that break SPA where the old app used in-app routing.
  2. Typing: avoid any on exported components, route params, and model shapes.
  3. Security and a11y: no untrusted dangerouslySetInnerHTML; preserve focus, labels, and keyboard behavior; env vars and URL semantics stay aligned or are explicitly documented.
  4. Styles: index.module.less next to index.tsx for pages; child components: .tsx + .module.less with the same basename.
  5. Vue-specific features: custom directives, plugins, defineExpose + parent refs must map to explicit React/Umi patterns (controlled props, forwardRef/useImperativeHandle, permission guards)—never silently drop behavior.
  6. Async and lists: clean up listeners and requests on unmount or dep changes; use stable ids for list keys, not indexes when order changes.
  7. Do not: run side effects during render; use useEffect for pure derivation; recreate EventBus / mixin / filter pipelines; mirror props to state without need; introduce a second global state stack for the same domain without a plan (prefer Umi models).

Additional constraints (often missed—verify explicitly)

  1. i18n: migrate vue-i18n keys/namespaces and locale switching to the chosen solution (including Umi locale plugins); avoid leftover hard-coded copy or mixed languages.
  2. HTTP and errors: use the shared request wrapper (and @umijs/max request APIs) so interceptors, error codes, auth headers, and global toasts match the old Vue layer; avoid ad-hoc fetch that bypasses global handling.
  3. Environment: map VITE_* / import.meta.env to Umi env / define; never ship secrets or internal-only URLs in the client bundle.
  4. Forms and tables: align Element validation rules, async validation, and blur/submit timing with antd Form; keep Table rowKey, pagination, sort, and filter params aligned with backend contracts; validate dynamic forms (Form.List, etc.) behavior-by-behavior.
  5. API scalars: keep explicit conversion between backend 0/1, stringly numbers, enums, and UI booleans—prefer normalization at submit/response boundaries to avoid silent drift.
  6. Build and deploy: publicPath / base, static asset URLs, and CDN prefixes match the old site or are documented; avoid production 404s for assets.
  7. Dev / integration: move mocks and dev proxy from the Vue setup into Umi conventions (mock/, proxy) so local and joint-debug environments stay consistent.
  8. SSR vs CSR: with Umi SSR, do not use window / document / localStorage on the server render path; with CSR-only, document any first-screen / SEO differences vs the legacy app.

Pre-release checklist

  • Routing, query, and auth behavior matches the legacy app (or differences are documented).
  • useEffect deps are complete; async work is cancelled or ignored when stale.
  • Pages include index.tsx + index.module.less; child style files match basename.
  • Custom directives/plugins/exposed methods have a mapped implementation or migration note.
  • Request layer, env vars, and deploy paths checked against Additional constraints.
  • Sample pass on critical forms/tables and i18n paths vs legacy behavior.

Style and structure

  • Prefer function components and hooks; emit → onXxx.
  • Keep feature boundaries similar to the Vue repo; page folder naming: see Vue SFC styles → Umi components below.

Stack and Umi mapping

Umi/antd APIs follow the official docs.

Target stack

Layer Choice
App framework @umijs/max (Umi 4)
UI Ant Design (antd)
Global state Umi data flow: src/models + useModel
Runtime React 18
Routing React Router v6 (via Umi; configure in config + routes)

Styling: Less + CSS Modules (*.module.less). Pages: PageName/index.tsx + PageName/index.module.less.

Routing and data (Umi)

Typical Vue pattern Umi + React
Fetch in onMounted after navigation useRequest, useModel, or useEffect + project request in page/layout
beforeEach auth access, route wrappers, or layout-level guards (see Umi docs)
Navigation / URL params useNavigate, useParams, useSearchParams, useLocation from @umijs/max or umi

Do not add a second standalone BrowserRouter root outside Umi.

Pinia / Vuex → Umi data flow

Vue Umi
Modular store src/models split by domain + useModel
Getters / derived Logic in models or useMemo in components
Async actions Model effects, or useRequest in pages then update model

Prefer useRequest for local request/cache when global state is not needed.

Vue SFC styles → Umi components

Vue React (Umi)
Page <style scoped> PageDir/index.tsx + index.module.less, import styles from './index.module.less'
Child scoped Foo.tsx + Foo.module.less in the same folder
<style lang="less"> Same content in the matching *.module.less

For HTTP, i18n, env, deploy, and mock constraints, see Additional constraints above.

Syntax examples

Vue vs React syntax; use @umijs/max, antd, and the rules above in real pages.

1. Counter

Vue 3 (<script setup>)

<script setup lang="ts">
import { ref } from 'vue'
const count = ref(0)
function inc() {
  count.value++
}
</script>
<template>
  <button type="button" @click="inc">{{ count }}</button>
</template>

React

import { useState } from 'react'

export function Counter() {
  const [count, setCount] = useState(0)
  return (
    <button type="button" onClick={() => setCount((c) => c + 1)}>
      {count}
    </button>
  )
}

2. Conditional list

Vue

<template>
  <ul v-if="items.length">
    <li v-for="item in items" :key="item.id">{{ item.name }}</li>
  </ul>
  <p v-else>No data</p>
</template>

React

return items.length ? (
  <ul>
    {items.map((item) => (
      <li key={item.id}>{item.name}</li>
    ))}
  </ul>
) : (
  <p>No data</p>
)

3. Controlled input

Vue

<input v-model="text" />

React

const [text, setText] = useState('')
<input value={text} onChange={(e) => setText(e.target.value)} />

4. Child events (emit)

Vue

<script setup lang="ts">
const emit = defineEmits<{ (e: 'update', v: number): void }>()
function notify() {
  emit('update', 1)
}
</script>

React

type Props = { onUpdate: (v: number) => void }
export function Child({ onUpdate }: Props) {
  function notify() {
    onUpdate(1)
  }
}

5. computed and watch

Vue

const doubled = computed(() => count.value * 2)
watch(count, (v) => console.log(v))

React

const doubled = useMemo(() => count * 2, [count])
useEffect(() => {
  console.log(count)
}, [count])

6. Provide / inject

Vue

provide('theme', 'dark')
const theme = inject('theme')

React

import { createContext, useContext, useMemo, useState } from 'react'

type Theme = 'light' | 'dark'
type ThemeContextValue = {
  theme: Theme
  setTheme: (v: Theme) => void
}

const ThemeContext = createContext<ThemeContextValue | null>(null)

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setTheme] = useState<Theme>('light')
  const value = useMemo(() => ({ theme, setTheme }), [theme])
  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
}

export function useTheme() {
  const ctx = useContext(ThemeContext)
  if (!ctx) throw new Error('useTheme must be used within ThemeProvider')
  return ctx
}

// usage:
// const { theme, setTheme } = useTheme()

7. Cleanup

Vue

onUnmounted(() => window.removeEventListener('resize', onResize))

React

useEffect(() => {
  window.addEventListener('resize', onResize)
  return () => window.removeEventListener('resize', onResize)
}, [])

8. Scoped slot → render prop

Vue

<Child v-slot="{ row }">
  <span>{{ row.name }}</span>
</Child>

React

<Child renderRow={(row) => <span>{row.name}</span>} />

9. Route params

Vue

const route = useRoute()
const id = route.params.id as string

Umi (same as React Router v6)

import { useParams } from '@umijs/max'
// or import { useParams } from 'umi'

const { id } = useParams<{ id: string }>()

10. React mental model: closure and deps

Common but not recommended

// stale closure: interval always sees initial count
useEffect(() => {
  const timer = setInterval(() => {
    setCount(count + 1)
  }, 1000)
  return () => clearInterval(timer)
}, []) // count is missing

Recommended

// use functional update to avoid stale closure
useEffect(() => {
  const timer = setInterval(() => {
    setCount((c) => c + 1)
  }, 1000)
  return () => clearInterval(timer)
}, [])

Common but not recommended

// derives data via effect + extra state
const [fullName, setFullName] = useState('')
useEffect(() => {
  setFullName(`${user.firstName} ${user.lastName}`)
}, [user.firstName, user.lastName])

Recommended

// derive directly in render / useMemo
const fullName = useMemo(
  () => `${user.firstName} ${user.lastName}`,
  [user.firstName, user.lastName]
)

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,014
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,013
Skill 文件
  • SKILL.md
    • Vue → UmiJS + React migration
    • Scope
    • Principles
    • API mapping (summary)
    • Constraints
      • Additional constraints (often missed—verify explicitly)
    • Pre-release checklist
    • Style and structure
    • Stack and Umi mapping
    • Target stack
    • Routing and data (Umi)
    • Pinia / Vuex → Umi data flow
    • Vue SFC styles → Umi components
    • Syntax examples
      • 1. Counter
      • 2. Conditional list
      • 3. Controlled input
      • 4. Child events (emit)
      • 5. computed and watch
      • 6. Provide / inject
      • 7. Cleanup
      • 8. Scoped slot → render prop
      • 9. Route params
      • 10. React mental model: closure and deps
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期