Composition API(四)

269 阅读1分钟

h 函数

作用

用来创建 vnode

使用

h 函数接收3个参数:

  • 一个 HTML 标签 / 一个组件(普通组件,或异步组件,或函数式组件)
  • 标签的属性 / 组件的 props
  • 标签的内容 / 组件的插槽

这3个参数是一一对应的。

h 函数的基本使用

h 函数可以用来渲染 HTML 标签

h 函数可以在两个地方使用:

  • render 函数中

  • setup 函数中

1. render 函数实现计数器案例

import { ref, h } from 'vue'

export default {
  setup() {
    const counter = ref(0)

    return {
      counter
    }
  },
  render() {
    return h('div', { class: 'app' }, [
      h('h3', null, `当前计数:${this.counter}`),
      h(
        'button',
        {
          onClick: () => {
            this.counter++
          }
        },
        '+1'
      ),
      h(
        'button',
        {
          onClick: () => {
            this.counter--
          }
        },
        '-1'
      )
    ])
  }
}

2. setup 函数实现计数器案例

import { ref, h } from 'vue'

export default {
  setup() {
    const counter = ref(0)

    return () => {
      return h('div', { class: 'app' }, [
        h('h3', null, `当前计数:${counter.value}`),
        h(
          'button',
          {
            onClick: () => {
              counter.value++
            }
          },
          '+1'
        ),
        h(
          'button',
          {
            onClick: () => {
              counter.value--
            }
          },
          '-1'
        )
      ])
    }
  }
}

image.png

setup 函数中使用 h 函数时需要将创建的 vnode 返回。

h 函数中组件跟插槽的使用

h 函数也可以渲染组件

import { h } from 'vue'
import HelloWorld from './HelloWorld.vue'

render() {
        return h(HelloWorld, null, '')
    }

子组件可以是普通组件,也可以是 函数组件

即:

<template>
  <div>
    <h3>hello world</h3>
  </div>
</template>

import { h } from 'vue'

export default {
  render() {
    return h('div', null, [h('h3', null, 'hello world')])
  }
}

函数组件:使用 render 函数来渲染的组件。

插槽的使用

h 函数渲染组件时,第三个参数就是插槽:

import { h } from 'vue'
import HelloWorld from './HelloWorld.vue'

export default {
  render() {
    return h(HelloWorld, null, {
      slotFirst: () => {
        return h('span', null, '我是插槽的内容')
      }
    })
  }
}

子组件是函数组件,通过 this.$slots 获取到所有的插槽 :

import { h } from 'vue'

export default {
  render() {
    return h('div', null, [
      h('h2', null, 'hello world'),
      this.$slots.slotFirst ? this.$slots.slotFirst() : h('span', null, '123')
    ])
  }
}

子组件是普通组件:

<template>
  <div>
    <h3>hello world</h3>
    <slot name="slotFirst"></slot>
  </div>
</template>

image.png