登录
原创

vue-render()函数

发布于 2021-11-24 阅读 656
  • 前端
  • Vue.js
原创

render()函数使用方法:

render() {
  const { h } = Vue
  return h('标签名', '标签的属性和对应属性值', '要传的内容')
}
// 可以嵌套传值
  return h('标签名', '标签的属性和对应属性值', [
    '要传的内容',
    h('标签名', '标签的属性和对应属性值', '要传的内容')
  ])

标签没有属性就写 - - - {}

多个标签之间的切换,可以考虑使用 render()函数,简化代码量

在vue中,标签元素的显示流程:
template模板 -》render()函数 -》h()函数 -》虚拟DOM(Json对象)-》 真实DOM -》展示到页面上

代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>render函数</title>
  <script src="https://unpkg.com/vue@next"></script>
  <style>
    body {
      color: palevioletred;
    }
  </style>
</head>
<body>
  <div id="root"></div>
</body>
<script>
  /* const app = Vue.createApp({
    data() {
      return {
        num: 1
      }
    },
    template: `
    <div>
      <test :level="num">
        你好波吉,我是卡克
      </test>
      <div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;波吉:你好呀~卡克,很开心认识你</div>
    </div>`
  })
  app.component('test', {
    props: ['level'],
    template: `
    <h1 v-if="level === 1"><slot /></h1>
    <h2 v-if="level === 2"><slot /></h2>
    <h3 v-if="level === 3"><slot /></h3>
    <h4 v-if="level === 4"><slot /></h4>
    <h5 v-if="level === 5"><slot /></h5>
    `
  }) */
  const app = Vue.createApp({
    data() {
      return {
        num: 2
      }
    },
    template: `
    <div>
      <test :level="num">
        卡克:你好波吉,我是卡克
      </test>
      <div>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;波吉:谢谢~卡克,很开心认识你</div>
    </div>`
  })
  app.component('test', {
    props: ['level'],
    render() {
      const { h } = Vue
      // return h('h'+ this.level, {}, this.$slots.default())
      return h('h'+ this.level, {}, [
        this.$slots.default(),
        h('h2', {}, '卡克:不管从今以后发生什么,我都想成为你的同伴!!')
      ])
    }
  })
  const vm = app.mount('#root')
</script>
</html>

页面效果:

image.png

评论区

零00
7粉丝

时光荏苒,我自清欢

0

2

0

举报