指令语法参考
组件导入
React 组件必须在 <script lang="react"> 块中导入:
md
<script lang="react">
import MyChart from './components/MyChart';
import { DataGrid } from './components/DataGrid';
</script>组件使用语法
md
<ComponentName directive prop="value" :bound-prop="vueData" />必须遵守:
- 使用自闭合标签:
<Comp />✓<Comp></Comp>✗ - 组件名必须与 import 完全匹配(区分大小写)
- 使用 PascalCase 命名
指令一览
| 指令 | 缩写 | 说明 |
|---|---|---|
ssr:only | - | 仅服务端渲染(默认) |
client:only | - | 仅客户端渲染 |
client:load | - | SSR + 立即 hydration |
client:visible | - | SSR + 可见时 hydration |
spa:sync-render | spa:sr | 路由切换同步渲染 |
spa:sync-render:disable | spa:sr:disable | 禁用同步渲染 |
Props 传递
静态 props(字符串):
md
<Chart title="销售数据" theme="dark" />动态 props(Vue 绑定):
md
<script setup>
const chartData = { labels: [...], values: [...] };
</script>
<Chart :data="chartData" :show-legend="true" />限制:
- 所有 props 最终序列化为字符串传递
- 不支持传递函数或事件处理器
- 这是初始化数据传递,非响应式绑定
Vue 组件嵌套
React 组件可嵌入 Vue 组件的 slot 中,接收 Vue 传递的数据:
md
<script setup>
import VueWrapper from './VueWrapper.vue';
</script>
<script lang="react">
import ReactChild from './ReactChild';
</script>
<VueWrapper>
<template #default="{ data }">
<ReactChild client:only :info="data" />
</template>
</VueWrapper>ssr:only 特殊能力
仅使用 ssr:only 的组件可访问 Node.js API:
tsx
// 可以在组件中使用
import { readFileSync } from 'node:fs';
import { join } from 'pathe';
const data = JSON.parse(
readFileSync(join(import.meta.dirname, 'data.json'), 'utf-8'),
);注意: 依赖本地文件的模块不支持 HMR,需手动配置 handleHotUpdate。
常见错误
| 错误 | 原因 | 修复 |
|---|---|---|
| 组件未渲染 | 未在 <script lang="react"> 中导入 | 添加导入语句 |
| 编译跳过警告 | 使用非自闭合标签 | 改为 <Comp /> |
| hydration 失败 | 组件依赖浏览器 API 但使用了 SSR | 改用 client:only |
| Props 为 undefined | 传递了函数类型 | 仅传递可序列化数据 |