vue中的render函数

创建一个HelloWorld组件:

复制代码
<script>
import Test from '@/components/Test'
export default {
  props: { tag: String },
  data() {
    return { arr: ['小王', '小明', '小红'] }
  },
  // template标签在vue内部会被编译成render函数
  render(createElement) {
    return createElement(
      this.tag, // 这里可以写 div li 等标签,可以由父组件传入,也可以写组件
      {},
      this.arr.map((item, index) =>
        createElement(
          // 'li',
          Test, // 这里渲染组件时,需要将 on 换成 nativeOn
          {
            props: { name: item, index },
            attrs: { class: 'my-li' },
            nativeOn: {
              click: () => {
                console.log('点击li', index)
              }
            }
          },
          item
        )
      )
    )
  },
  components: { Test }
}
</script>
复制代码

Test.vue:

复制代码
<script>
export default {
  props: { name: String, index: Number },
  render(h) {
    return h(
      'li',
      {
        style: {
          color: 'orange',
          fontWeight: 'bold'
        },
        on: {
          click: () => {
            console.log('点击li了', this.index)
          }
        }
      },
      `name:${this.name}`
    )
  }
}
</script>
复制代码

App.vue中引入和使用:

复制代码
<template>
  <div id="app">
    <HelloWorld tag='ul' />
  </div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld'
export default {
  components: { HelloWorld }
}
</script>
复制代码

 

效果:

 

createElement函数的参数:

参数一:需要渲染成什么标签,可以是props接收的值,也可以是一个组件

参数二:配置项,attrs设置标签属性,on设置标签事件,nativeOn设置原生事件(当渲染组件时需要在nativeOn中设置事件),style设置样式,props设置子组件的值

参数三:标签的内容

 

posted @   吴小明-  阅读(449)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
历史上的今天:
2019-08-02 vue 获取时间戳对象转换为日期格式
点击右上角即可分享
微信分享提示