vue通过$createElement创建节点渲染
创始人
2024-11-10 17:43:08

createElement 参数icon-default.png?t=N7T8https://v2.cn.vuejs.org/v2/guide/render-function.html

$createElement参数tag完整的数据对象如下

const h = this.$createElement; h('div', tag, [     h('span', tag, '内容1'),     h('span', tag, '内容2'), ])  // tag完整的数据对象如下: const tag = {   // 与 `v-bind:class` 的 API 相同,   // 接受一个字符串、对象或字符串和对象组成的数组   'class': {     foo: true,     bar: false   },   // 与 `v-bind:style` 的 API 相同,   // 接受一个字符串、对象,或对象组成的数组   style: {     color: 'red',     fontSize: '14px'   },   // 普通的 HTML attribute   attrs: {     id: 'foo'   },   // 组件 prop   props: {     myProp: 'bar'   },   // DOM property   domProps: {     innerHTML: 'baz'   },   // 事件监听器在 `on` 内,   // 但不再支持如 `v-on:keyup.enter` 这样的修饰器。   // 需要在处理函数中手动检查 keyCode。   on: {     click: this.clickHandler   },   // 仅用于组件,用于监听原生事件,而不是组件内部使用   // `vm.$emit` 触发的事件。   nativeOn: {     click: this.nativeClickHandler   },   // 自定义指令。注意,你无法对 `binding` 中的 `oldValue`   // 赋值,因为 Vue 已经自动为你进行了同步。   directives: [     {       name: 'my-custom-directive',       value: '2',       expression: '1 + 1',       arg: 'foo',       modifiers: {         bar: true       }     }   ],   // 作用域插槽的格式为   // { name: props => VNode | Array }   scopedSlots: {     default: props => createElement('span', props.text)   },   // 如果组件是其它组件的子组件,需为插槽指定名称   slot: 'name-of-slot',   // 其它特殊顶层 property   key: 'myKey',   ref: 'myRef',   // 如果你在渲染函数中给多个元素都应用了相同的 ref 名,   // 那么 `$refs.myRef` 会变成一个数组。   refInFor: true }

完整示例

const getChildrenTextContent = function (children) {   return children.map(function (node) {     return node.children       ? getChildrenTextContent(node.children)       : node.text   }).join('') }  Vue.component('anchored-heading', {   render: function (createElement) {     // 创建 kebab-case 风格的 ID     const headingId = getChildrenTextContent(this.$slots.default)       .toLowerCase()       .replace(/\W+/g, '-')       .replace(/(^-|-$)/g, '')      return createElement(       'h' + this.level,       [         createElement('a', {           attrs: {             name: headingId,             href: '#' + headingId           }         }, this.$slots.default)       ]     )   },   props: {     level: {       type: Number,       required: true     }   } })

相关内容

热门资讯

裸辞做“一人公司”,我后悔了 去年这个时候,一位以色列程序员正在东南亚旅行。他顺手把一个在脑子里转了很久的想法做成了产品,一个让任...
南京建成国内首个Pre-6G试... 4月21日,2026全球6G技术与产业生态大会在南京开幕。全息互动技术展台前,一名远在北京的工作人员...
超梵求职受邀参加“2025抖音... 超梵求职受邀参加“2025抖音巨量引擎成人教育行业生态大会”,探讨分享优质内容传播,服务万千学员。 ...
摩托罗拉Razr 2026(R... IT之家 4 月 22 日消息,摩托罗拉宣布新一代 Razr 折叠手机将于 4 月 29 日在美国发...
库克卸任,特纳斯领航:苹果新纪... 苹果首席执行官蒂姆·库克将卸任,硬件工程主管约翰·特纳斯将接任,苹果公司今天宣布此事。 库克将在夏季...