render函数使用

<script>
export default {
  data () {
    return {
      item: ['张三','李四','小明']
    }
  },
  // 在组件中使用,去除组件中的template标签  (组件中的template标签中的内容编译时最终都会编译成render函数)
  // createElement参数配置请看vue官网 https://cn.vuejs.org/v2/guide/render-function.html
  /* 
    createElement();
    第一个参数(必要参数):主要用于提供dom的html内容,类型可以是字符串、对象或函数
    第二个参数(类型是对象,可选):用于设置这个dom的一些样式、属性、传的组件的参数、绑定事件之类
    第三个参数(类型是数组,数组元素类型是vnode,可选):主要是指该结点下还有其他结点,用于设置分发的内容,包括新增的其他组件。注意,组件树中的所有vnode必须是唯一的
  */

  render: function (h) {
    console.log(h);
    // return createElement(
    //   "div",
    //   {},
    //   this.item.map(name => {
    //     return createElement('span', {
    //       class: 'box',
    //       on: {
    //         click: this.handlerClick
    //       }
    //     }, name);
    //   })
    // );


    // jsx写法
    return (
      <div class={'box'} onclick={this.handlerClick}>
        { this.item.map(name => { return <span>{ name }</span> }) }
      </div>
    )
  },
  methods: {
    handlerClick() {
      console.log('click');
    }
  }
};
</script>
<style scoped>
  .box {
    color: red;
    font-size: 50px;
    display: block;
  }
</style>

页面显示

createElement传入一个组件
<script>
import msg from "./components/msg.vue";
export default {
  render: function (h) {
    console.log(h);
    // createElement第一个参数也可以传入一个组件
    // return h(msg, {
    //   props: {
    //     msg1: 'css',
    //     msg2: 'html',
    //     msg3: 'javascript',
    //   },
    // });


    // jsx写法
    return (
      <msg msg1={'css'} msg2={'html'} msg3={'javascript'} />
    )
  },
};
</script>
<template>
  <ul>
    <li>{{ msg1 }}</li>
    <li>{{ msg2 }}</li>
    <li>{{ msg3 }}</li>
  </ul>
</template>
<script>
export default {
  props: {
    msg1: String,
    msg2: String,
    msg3: String,
  }
}
</script>
<style scoped>
  li {
    font-size: 50px;
    color: red;
  }
</style>

页面显示

render函数使用场景

<template>
  <div>
    <level :level="1">hello world1</level>
    <level :level="2">hello world2</level>
    <level :level="3">hello world3</level>
    <level :level="4">hello world4</level>
    <level :level="5">hello world5</level>
    <level :level="6">hello world6</level>
  </div>
</template>
<script>
import Level from './components/level.vue'
export default {
  components: {
    Level
  }
};
</script>
<style scoped>

</style>
<script>
export default {
  props: {
    level: Number
  },
  render: function (h) {
    console.log(h);
    console.log(this.$slots);
    // return createElement(`h${this.level}`, this.$slots.default, );

    // jsx写法
    const tag = `h${this.level}`;
    return (
      <tag>
        { this.$slots.default }
      </tag>
    )
  }
}
</script>

页面显示

 
原文地址:https://www.cnblogs.com/ltog/p/14331854.html