Skip to content

Latest commit

 

History

History
162 lines (134 loc) · 3.25 KB

directives.md

File metadata and controls

162 lines (134 loc) · 3.25 KB

Directives

Vue built-in directives for JSX.

Directive Vue Volar
v-if, v-else-if, v-else
v-slot, v-slots
v-for
v-model
v-html, v-text /
v-once /

Dynamic Arguments

It is also possible to use a variable in a directive argument. Because JSX doesn't support [] keyword, use $ instead.

Modifiers

Modifiers are special postfixes denoted by a _, which indicate that a directive should be bound in some special way. Because JSX doesn't support . keyword, we use _ instead.

<form onSubmit_prevent>
  <input v-model_number={value} />
</form>

v-if, v-else-if, v-else

export default ({ foo = 0 }) => {
  // ---cut-start---
  // prettier-ignore
  // ---cut-end---
  return (
    <>
      <div v-if={foo === 0}>{foo}</div>

      <div v-else-if={foo === 1}>{foo}</div>
      //                          ^?

      <div v-else>{foo}</div>
      //           ^?
    </>
  )
}

v-for

export default () => (
  <div v-for={(item, index) in 4} key={index}>
    {item}
  </div>
)

v-slot, v-slots

::: code-group

const Comp = () => {
  defineSlots<{
    default: () => any
    slot: (scope: { bar: number }) => any
    slots: (scope: { baz: boolean }) => any
  }>()
  return <div />
}

// ---cut-start---
// prettier-ignore
// ---cut-end---
export default () => (
  <Comp>
    default slot
    <template v-slot:slot={{ bar }}>
      //              ^|
      {bar}
    </template>
  </Comp>
)
const Comp = () => {
  defineSlots<{
    default: () => any
    slot: (scope: { bar: number }) => any
    slots: (scope: { baz: boolean }) => any
  }>()
  return <div />
}

export default () => (
  <Comp
    v-slots={{
      default: () => <>default slot</>,
      slot: ({ bar }) => <>{bar}</>,
    }}
  />
)

:::

v-model

import { ref } from 'vue'

const Comp = () => {
  const model = defineModel<string>('model')
  const models = defineModel<string[]>('models')
  return <div />
}

export default () => {
  const foo = ref('')
  const name = ref('model')
  return (
    <Comp
      v-model:$name_value$={foo.value}
      v-model:model={foo.value}
      //       ^|
    />
  )
}

v-slot

export const Comp = () => {
  defineSlots<{
    default: (scope: { foo: string }) => any
    title: (scope: { bar: number }) => any
  }>()
  return <div />
}

const slots = defineSlots<{
  default: (scope: { foo: string }) => any
  title: (scope: { bar: number }) => any
}>()

// ---cut-start---
// prettier-ignore
// ---cut-end---
export default () => (
  <Comp>
    <template v-for={(Slot, name) in slots} v-slot:$name$={scope}>
      //                                             ^?
      <Slot v-if={Slot} {...scope} />
    </template>
  </Comp>
)