文明其精神,野蛮其体魄。🍺|

yunChuans

园龄:3年4个月粉丝:6关注:0

vue中的渲染函数

介绍

Vue 推荐在绝大多数情况下使用模板来创建你的 HTML。然而在一些场景中,你真的需要 JavaScript 的完全编程的能力。这时你可以用渲染函数,它比模板更接近编译器。

案例

有父子组件,根据父组件传过来的值,子组件显示不同的h。

子组件 test.js

export default {
  props: {
    level: Number,
  },
  render(h) {
    return h(`h${this.level}`, this.$slots.default);
  },
};

父组件

<template>
  <div>
    <Test :level="1">
      HelloWorld
    </Test>
    <Test :level="2">
      hahahah
    </Test>
  </div>
</template>

<script>
import Test from './test';

export default {
  components: {
    Test,
  },
};
</script>

<style module lang="scss">
.testclass {
  width: 200px;
  height: 200px;
  background-color: pink;
}
</style>

效果

image

h函数参数

h函数(createElement)接受三个参数

render: function(createElement) {
          let _this = this['$options'].parent  //指向父级hello (之前写成)
          console.log(_this);
      return createElement (
        // 第一个参数 创建的标签名
        "div",
        //第二个参数 给创建的标签加属性
        {
          //加个类名
          'class': "new-div",
          // 加个插槽
          scopedSlots: {
            haha: props => createElement ('p',props.text)
          },
          on: {
            click:  _this.clickHandler
          }
        },
        // 第三个参数,给上面添加的div内再加点子元素(也是和上面一样,有三个参数,无值时可以使用null)
        [
          createElement (
            'h1',
            null,
            "这是渲染出来的h1标签"
          ),
          createElement(
                  'a', 
                  {
                      attrs: {
                          href: 'https://www.baidu.com'
                      }
                  }, 
                  '百度'
          ),
          createElement(
            'button',
            {
              on: {
                click:  _this.clickHandler
              }
            },
            '这是个按钮'
          )
        ]
      )
    }

本文作者:yunChuans

本文链接:https://www.cnblogs.com/zychuan/p/17109482.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   yunChuans  阅读(179)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 恋ダコ (茧•爱) 恋ダコ
  2. 2 君がいて水になる 正しい偽りからの起床
君がいて水になる - 正しい偽りからの起床
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.