渲染函数
#
dynamically render tagsinput:
<example :tags="['h1', 'h2', 'h3']"></example>
output:
<div> <h1>0</h1> <h2>1</h2> <h3>2</h3></div>
要实现上述 🌰 的功能,先让我们看看什么是渲染函数。在单文件 vue 组件中,使用template
语法书写 HTML,然后经过转译成 VNode。
使用 render 函数可以用 JS 构建 虚拟 DOM,这样就节省了转译的过程。
当使用 render 函数描述虚拟 DOM 时,vue 提供一个函数,这个函数是构建虚拟 DOM 所需要的工具。官网上给他起了个名字
叫 createElement
,还有约定简写 h
。
实现代码
<script src="https://lib.baomitu.com/vue/2.6.14/vue.common.dev.js"></script>
<div id="app"> <example :tags="['h1', 'h2', 'h3']"></example></div>
<script> Vue.component("example", { functional: true, props: { tags: { type: Array, validator(arr) { return !!arr.length; }, }, }, render: (h, context) => { const tags = context.props.tags; return h( "div", context.data, tags.map((tag, index) => h(tag, index)) ); }, });
new Vue({ el: "#app" });</script>