jsxDirective
稳定性:
稳定
在 JSX 中使用 Vue 内置指令。
指令 | Vue 3 | Vue 2 | Volar |
---|---|---|---|
v-if | ✅ | ✅ | ✅ |
v-else-if | ✅ | ✅ | ✅ |
v-else | ✅ | ✅ | ✅ |
v-for | ✅ | ✅ | ✅ |
v-on | ✅ | ✅ | ✅ |
v-slot | ✅ | ✅ | ✅ |
v-html | ✅ | ✅ | / |
v-once | ✅ | ❌ | / |
v-memo | ✅ | ❌ | / |
选项
ts
interface Options { /** * @default 'v-' */ prefix?: string /** * @default 'vue' */ lib?: 'vue' | 'react' | 'preact' | 'solid' | string }
用法
v-if
, v-else-if
, v-else
vue
<script setup lang="tsx"> const { foo } = defineProps<{ foo: number }>() export default () => ( <> <div v-if={foo === 0}>{foo}</div> <div v-else-if={foo === 1}>{foo}</div> <div v-else>{foo}</div> </> ) </script>
v-for
vue
<script setup lang="tsx"> export default () => ( <div v-for={(item, index) in 4} key={index}> {item} </div> ) </script>
v-slot
vue
<script lang="tsx" setup> import { Comp } from './Comp.tsx' export default () => ( <Comp> default slot... <template v-slot:slot={{ bar }}> {bar} </template> </Comp> ) </script>
tsx
import type { FunctionalComponent } from 'vue' export const Comp: FunctionalComponent< {}, {}, { default: () => any slot: (scope: { bar: number }) => any slots: (scope: { baz: boolean }) => any } > = () => <div />
v-on
WARNING
v-on
仅支持绑定不带参数的事件/监听器对的对象。
tsx
<form v-on={{ submit }} />
动态参数
在指令参数上也可以使用一个变量,需要包含在一对 $
内:
v-model
vue
<script setup lang="tsx"> import { Comp } from './Comp.tsx' const name = ref('model') const model = defineModel<string>() export default () => ( <Comp v-model:$name$={model.value} v-model:model={model.value} /> ) </script>
tsx
import { ref, type FunctionalComponent } from 'vue' export const Comp: FunctionalComponent< { model: string models: string[] }, { 'update:model': [value: string] 'update:models': [value: string[]] } > = () => <div />
v-slot
vue
<script setup lang="tsx"> import { Comp } from './Comp.tsx' const slots = defineSlots<{ default: (scope: { foo: string }) => any title: (scope: { bar: number }) => any }>() export default () => ( <Comp> <template v-for={(Slot, name) in slots} v-slot:$name$={scope}> <Slot {...scope} /> </template> </Comp> ) </script>
tsx
import type { FunctionalComponent } from 'vue' export const Comp: FunctionalComponent< {}, {}, { default: (scope: { foo: string }) => any title: (scope: { bar: number }) => any } > = () => <div />
修饰符
修饰符是以 _
开头的特殊后缀,表明指令需要以一些特殊的方式被绑定。
tsx
<form onSubmit_prevent> <input v-model_number={value} /> </form>
Volar 配置
jsonc
{ "vueCompilerOptions": { "plugins": ["vue-macros/volar"], }, }