Перечислите эквиваленты шаблонов в функциях рендеринга?vue-71

Функции рендеринга (render functions) в Vue предоставляют более гибкую альтернативу шаблонам. Рассмотрим эквиваленты основных шаблонных конструкций в render-функциях.

Основные эквиваленты

1. Директивы v-if / v-else

Шаблон:

<div v-if="condition">Content</div>
<div v-else>Alternative</div>

Render-функция:

render(h) {
  return this.condition
    ? h('div', 'Content')
    : h('div', 'Alternative')
}

2. Директива v-for

Шаблон:

<ul>
  <li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>

Render-функция:

render(h) {
  return h('ul',
    this.items.map(item =>
      h('li', { key: item.id }, item.text)
    )
}

3. Директива v-model

Шаблон:

<input v-model="message">

Render-функция:

render(h) {
  return h('input', {
    domProps: { value: this.message },
    on: {
      input: e => { this.message = e.target.value }
    }
  })
}

4. Слоты

Шаблон:

<child-component>
  <template v-slot:default>Default Slot</template>
  <template v-slot:named>Named Slot</template>
</child-component>

Render-функция:

render(h) {
  return h('child-component', {
    scopedSlots: {
      default: () => 'Default Slot',
      named: () => 'Named Slot'
    }
  })
}

5. Динамические атрибуты

Шаблон:

<div :class="dynamicClass" :style="dynamicStyle"></div>

Render-функция:

render(h) {
  return h('div', {
    class: this.dynamicClass,
    style: this.dynamicStyle
  })
}

6. Обработка событий

Шаблон:

<button @click="handleClick">Click</button>

Render-функция:

render(h) {
  return h('button', {
    on: {
      click: this.handleClick
    }
  }, 'Click')
}

7. Динамические компоненты

Шаблон:

<component :is="currentComponent" />

Render-функция:

render(h) {
  return h(this.currentComponent)
}

Продвинутые эквиваленты

1. Модификаторы событий

Шаблон:

<input @keyup.enter="submit">

Render-функция:

render(h) {
  return h('input', {
    on: {
      keyup: e => {
        if (e.key === 'Enter') this.submit()
      }
    }
  })
}

2. Пользовательские директивы

Шаблон:

<div v-custom-directive:arg.modifier="value"></div>

Render-функция:

render(h) {
  return h('div', {
    directives: [{
      name: 'custom-directive',
      value: this.value,
      arg: 'arg',
      modifiers: { modifier: true }
    }]
  })
}

3. Функциональные компоненты

Шаблон:

<template functional>
  <div>{{ props.message }}</div>
</template>

Render-функция:

Vue.component('functional-comp', {
  functional: true,
  render(h, { props }) {
    return h('div', props.message)
  }
})

Практический пример преобразования

Шаблон:

<div class="container">
  <h1 v-if="title">{{ title }}</h1>
  <ul>
    <li v-for="item in items" @click="selectItem(item)">
      {{ item.name }}
    </li>
  </ul>
</div>

Эквивалентная render-функция:

render(h) {
  const children = []

  if (this.title) {
    children.push(h('h1', this.title))
  }

  const listItems = this.items.map(item =>
    h('li', {
      on: {
        click: () => this.selectItem(item)
      }
    }, item.name)
  )

  children.push(h('ul', listItems))

  return h('div', { class: 'container' }, children)
}

Резюмируем:

render-функции предоставляют полный эквивалент шаблонных возможностей Vue, но с более явным и гибким синтаксисом. Понимание этих соответствий критически важно для работы с динамическими компонентами, JSX и сложными сценариями рендеринга.