Vue.js Render函数详解:从基础到插槽应用

作者:山岚

时间:2026-10-24

浏览:221

本文详解Vue.js中render函数的使用方法。介绍createElement的三个参数,包括标签名、数据对象和子节点。通过示例演示如何生成h1-h6标签及使用slot插入内容,展示render函数在复杂组件构建中的优势。

文章目录

Vue 建议在大多数场景下优先使用 template 来构建 HTML。但当需要完全掌控 JavaScript 编程能力时,render 函数便派上用场,它比 template 更贴近编译器底层。

组件接口定义与 Render 函数基础

在 HTML 层面,我们定义组件接口:通过传入 level 参数(1-6)生成对应的 h1 至 h6 标签,并利用 slot 插入内容。


<div id="div1">
    <child :level="1">Hello world!</child>
</div>

<script type="text/x-template" id="child-template">
  <h1 v-if="level === 1">
    <slot></slot>
  </h1>
  <h2 v-if="level === 2">
    <slot></slot>
  </h2>
  <h3 v-if="level === 3">
    <slot></slot>
  </h3>
  <h4 v-if="level === 4">
    <slot></slot>
  </h4>
  <h5 v-if="level === 5">
    <slot></slot>
  </h5>
  <h6 v-if="level === 6">
    <slot></slot>
  </h6>
</script>

<script type="text/javascript">
    /**
     * 全局注册child组件,注意template如果值以 # 开始,则它用作选项符,将使用匹配元素的 innerHTML 作为模板。常用的技巧是用 <script type="x-template"> 包含模板,这样的好处是html不会渲染里面的内容
     * 
     * 这里使用template不是最好的选择:
     *    一、代码冗长 
     *    二、在不同的标题插入内容需要重复使用slot 
     *    三、由于组件必须有根元素,所以标题和内容被包裹在一个无用的div中,比如<div><h1>hello world</h1></div>
     */

    Vue.component('child', {
      template: '#child-template',
      props: {
        level: {
          type: Number,
          required: true
        }
      },
      data: function() {
        return {
          a: 1
        }
      }
    })

    new Vue({
        el:"#div1"
    })
  </script>

接下来尝试使用 render 函数实现上述功能。需注意,一旦使用 render 函数,template 选项将被忽略。

createElement 函数接收三个参数:

第一个参数指定 HTML 标签名、组件或函数,此为必填项;第二个参数为可选的数据对象 {Object}。

具体示例如下:

Render 函数实战:参数与插槽应用


<div id="div1">
    <child :level="1">
        Hello world!
    </child>
    <child :level="2">
        <!-- 将不会被显示 -->
        <span slot="footer">this is footer slot</span>
        <p slot="header">this is header slot</p>
    </child>
</div>


<script>
    Vue.component('child', {
        render: function (createElement) {
            console.log(this.$slots);
            return createElement(
                'h' + this.level, // tagName标签名称
                {
                    // 为每个h标签设置class
                    'class': {
                        foo: true,
                        bar: false
                    },
                    // 最终被渲染为内联样式
                    style: {
                        color: 'red',
                        fontSize: '14px'
                    },
                    // 其他的html属性
                    attrs: {
                        id: 'foo',
                        'data-id': 'bar'
                    },
                    // DOM属性
                    domProps: {
                        // innerHTML: 'from domProps',
                    },
                    // 事件监听器基于 "on"
                    // 所以不再支持如 v-on:keyup.enter 修饰器
                    on: {
                        click: this.clickHandler
                    },
                    // ...
                },
                // 你可以从this.$slots获取VNodes列表中的静态内容
                // $slots.default用来访问组件的不具名slot
                // 当你可能需要具名slot的时候需要指定slot的name, this.$slots.header
                // [this.$slots.default,this.$slots.footer,this.$slots.header] //显示level2插槽
                [this.$slots.default]  //只显示不具名slot
            )
        },
        template: '<div v-if="level===1"><slot></slot></div>', // 将被忽略
        props: {
            level: {
                type: Number,
                required: true
            }
        },
        methods: {
            clickHandler: function () {
                console.log('clickHandler')
            }
        }
    })

    new Vue({
        el: "#div1"
    })
</script>

渲染结果如下:

组件接口定义与 Render 函数基础

本文介绍了 Vue.js render 函数的使用方法,更多相关内容请参考本站其他文章或继续浏览后续内容,感谢支持!

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章