[Vue] Use render function

Sometime when doing thing is harder in template syntax, you can switch to using render function intead.

For example, we have s Stackcomponent, it dynamically wrapping child element with a div and some default styling applied.

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      .mt-4 {
        margin: 10px;
      }
    </style>
    <script src="https://unpkg.com/vue@3.0.11/dist/vue.global.js"></script>
  </head>
  <body>
    <div id="app"></div>

    <script>
      const {h, createApp} = Vue

      const Stack = {
        props: {
          size: {
            type: String,
            default: '1',
          }
        },
        render() {
          const slot = this.$slots.default
            ? this.$slots.default()
            : [];
          return h('div', {class: 'stack'}, slot.map(child => {
            return h('div', {class: `mt-${this.$props.size}`}, [child])
          }))
        }
      }

      const App = {
        components: {
          Stack
        },
        template: `
          <Stack size="4">
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <Stack size="4">
              <div>3.1</div>
              <div>3.2</div>
              <div>3.3</div>
                <Stack size="4">
                  <div>4.1</div>
                  <div>4.2</div>
                  <div>4.3</div>
                </Stack>
            </Stack>
          </Stack>
        `
      }

      const mountedApp = createApp(App).mount('#app')
    </script>
  </body>
</html>

This is easier to do with render function.

posted @   Zhentiw  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2023-11-23 [Javascript] Sanitizing User Input in Javascript
2022-11-23 [XState + Typescript] Type XState
2022-11-23 [XState + React] using @xstate/inspect to display state machine char in webapp
2020-11-23 [Tools] API Extractor Setup for Typescript
2015-11-23 [Protractor] Testing With Protractor Page Objects
2015-11-23 [Protractor] Test Simple Binding With Protractor
2015-11-23 [Angular 2] A Simple Form in Angular 2
点击右上角即可分享
微信分享提示