Render Functions & JSX·续

function render() { return h('div', [h(Foo), h(Bar)]) }


```jsx
function render() {
  return (
    <div>
      <Foo />
      <Bar />
    </div>
  )
}

As we can see, h can work with components imported from any file format as long as it's a valid Vue component.

Dynamic components are straightforward with render functions:

import Foo from './Foo.vue'
import Bar from './Bar.jsx'

function render() {
  return ok.value ? h(Foo) : h(Bar)
}
function render() {
  return ok.value ? <Foo /> : <Bar />
}

If a component is registered by name and cannot be imported directly (for example, globally registered by a library), it can be programmatically resolved by using the resolveComponent() helper.

Rendering Slots

In render functions, slots can be accessed from the setup() context. Each slot on the slots object is a function that returns an array of vnodes:

export default {
  props: ['message'],
  setup(props, { slots }) {
    return () => [
      // default slot:
      // <div><slot /></div>
      h('div', slots.default()),

// named slot:
      // <div><slot name="footer" :text="message" /></div>
      h(
        'div',
        slots.footer({
          text: props.message
        })
      )
    ]
  }
}

JSX equivalent:

// default
<div>{slots.default()}</div>

// named
<div>{slots.footer({ text: props.message })}</div>

In render functions, slots can be accessed from this.$slots:

export default {
  props: ['message'],
  render() {
    return [
      // <div><slot /></div>
      h('div', this.$slots.default()),

// <div><slot name="footer" :text="message" /></div>
      h(
        'div',
        this.$slots.footer({
          text: this.message
        })
      )
    ]
  }
}

JSX equivalent:

// <div><slot /></div>
<div>{this.$slots.default()}</div>

// <div><slot name="footer" :text="message" /></div>
<div>{this.$slots.footer({ text: this.message })}</div>

Passing Slots

Passing children to components works a bit differently from passing children to elements. Instead of an array, we need to pass either a slot function, or an object of slot functions. Slot functions can return anything a normal render function can return - which will always be normalized to arrays of vnodes when accessed in the child component.

// single default slot
h(MyComponent, () => 'hello')

// named slots
// notice the `null` is required to avoid
// the slots object being treated as props
h(MyComponent, null, {
  default: () => 'default slot',
  foo: () => h('div', 'foo'),
  bar: () => [h('span', 'one'), h('span', 'two')]
})

JSX equivalent:

// default
<MyComponent>{() => 'hello'}</MyComponent>

// named
<MyComponent>{{
  default: () => 'default slot',
  foo: () => <div>foo</div>,
  bar: () => [<span>one</span>, <span>two</span>]
}}</MyComponent>

Passing slots as functions allows them to be invoked lazily by the child component. This leads to the slot's dependencies being tracked by the child instead of the parent, which results in more accurate and efficient updates.

Scoped Slots

To render a scoped slot in the parent component, a slot is passed to the child. Notice how the slot now has a parameter text. The slot will be called in the child component and the data from the child component will be passed up to the parent component.

// parent component
export default {
  setup() {
    return () => h(MyComp, null, {
      default: ({ text }) => h('p', text)
    })
  }
}

Remember to pass null so the slots will not be treated as props.

// child component
export default {
  setup(props, { slots }) {
    const text = ref('hi')
    return () => h('div', null, slots.default({ text: text.value }))
  }
}

JSX equivalent:

<MyComponent>{{
  default: ({ text }) => <p>{ text }</p>  
}}</MyComponent>

Built-in Components

Built-in components such as <KeepAlive>, <Transition>, <TransitionGroup>, <Teleport> and <Suspense> must be imported for use in render functions:

import { h, KeepAlive, Teleport, Transition, TransitionGroup } from 'vue'

export default {
  setup () {
    return () => h(Transition, { mode: 'out-in' }, /* ... */)
  }
}
import { h, KeepAlive, Teleport, Transition, TransitionGroup } from 'vue'

export default {
  render () {
    return h(Transition, { mode: 'out-in' }, /* ... */)
  }
}

v-model

The v-model directive is expanded to modelValue and onUpdate:modelValue props during template compilation—we will have to provide these props ourselves:

export default {
  props: ['modelValue'],
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    return () =>
      h(SomeComponent, {
        modelValue: props.modelValue,
        'onUpdate:modelValue': (value) => emit('update:modelValue', value)
      })
  }
}
export default {
  props: ['modelValue'],
  emits: ['update:modelValue'],
  render() {
    return h(SomeComponent, {
      modelValue: this.modelValue,
      'onUpdate:modelValue': (value) => this.$emit('update:modelValue', value)
    })
  }
}

Custom Directives

Custom directives can be applied to a vnode using withDirectives:

import { h, withDirectives } from 'vue'

// a custom directive
const pin = {
  mounted() { /* ... */ },
  updated() { /* ... */ }
}

// &lt;div v-pin:top.animate="200">&lt;/div>
const vnode = withDirectives(h('div'), [
  [pin, 200, 'top', { animate: true }]
])

If the directive is registered by name and cannot be imported directly, it can be resolved using the resolveDirective helper.

Template Refs

With the Composition API, when using useTemplateRef() template refs are created by passing the string value as prop to the vnode:

import { h, useTemplateRef } from 'vue'

export default {
  setup() {
    const divEl = useTemplateRef('my-div')

// &lt;div ref="my-div">
    return () => h('div', { ref: 'my-div' })
  }
}

In versions before 3.5 where useTemplateRef() was not introduced, template refs are created by passing the ref() itself as a prop to the vnode:

import { h, ref } from 'vue'

export default {
  setup() {
    const divEl = ref()

// &lt;div ref="divEl">
    return () => h('div', { ref: divEl })
  }
}

With the Options API, template refs are created by passing the ref name as a string in the vnode props:

export default {
  render() {
    // &lt;div ref="divEl">
    return h('div', { ref: 'divEl' })
  }
}

Functional Components

Functional components are an alternative form of component that don't have any state of their own. They act like pure functions: props in, vnodes out. They are rendered without creating a component instance (i.e. no this), and without the usual component lifecycle hooks.

To create a functional component we use a plain function, rather than an options object. The function is effectively the render function for the component.

The signature of a functional component is the same as the setup() hook:

function MyComponent(props, { slots, emit, attrs }) {
  // ...
}

As there is no this reference for a functional component, Vue will pass in the props as the first argument:

function MyComponent(props, context) {
  // ...
}

The second argument, context, contains three properties: attrs, emit, and slots. These are equivalent to the instance properties $attrs, $emit, and $slots respectively.

Most of the usual configuration options for components are not available for functional components. However, it is possible to define props and emits by adding them as properties:

MyComponent.props = ['value']
MyComponent.emits = ['click']

If the props option is not specified, then the props object passed to the function will contain all attributes, the same as attrs. The prop names will not be normalized to camelCase unless the props option is specified.

For functional components with explicit props, attribute fallthrough works much the same as with normal components. However, for functional components that don't explicitly specify their props, only the class, style, and onXxx event listeners will be inherited from the attrs by default. In either case, inheritAttrs can be set to false to disable attribute inheritance:

MyComponent.inheritAttrs = false

Functional components can be registered and consumed just like normal components. If you pass a function as the first argument to h(), it will be treated as a functional component.

Typing Functional Components

Functional Components can be typed based on whether they are named or anonymous. Vue - Official extension also supports type checking properly typed functional components when consuming them in SFC templates.

Named Functional Component

import type { SetupContext } from 'vue'
type FComponentProps = {
  message: string
}

type Events = {
  sendMessage(message: string): void
}

function FComponent(
  props: FComponentProps,
  context: SetupContext&lt;Events>
) {
  return (
    &lt;button onClick={() => context.emit('sendMessage', props.message)}>
        {props.message} {' '}
    &lt;/button>
  )
}

FComponent.props = {
  message: {
    type: String,
    required: true
  }
}

FComponent.emits = {
  sendMessage: (value: unknown) => typeof value === 'string'
}

Anonymous Functional Component

import type { FunctionalComponent } from 'vue'

type FComponentProps = {
  message: string
}

type Events = {
  sendMessage(message: string): void
}

const FComponent: FunctionalComponent&lt;FComponentProps, Events> = (
  props,
  context
) => {
  return (
    &lt;button onClick={() => context.emit('sendMessage', props.message)}>
        {props.message} {' '}
    &lt;/button>
  )
}

FComponent.props = {
  message: {
    type: String,
    required: true
  }
}

FComponent.emits = {
  sendMessage: (value) => typeof value === 'string'
}


url: /guide/extras/web-components.md