VUE render VS template

render VS template

  1. VUE一般使用template来创建HTML,而使用javascript来创建html要使用render函数。

  2. template逻辑简单,理解起来相对容易,但灵活性不足;render渲染方式可以将JS发挥到极致,通过createElement的方式创建虚拟DOM。其逻辑性较强,适合复发的组件封装。

  3. render(高)的性能要比tempate(低)要高

  4. render函数的优先级大于template(优先级可能会误导我们的理解,换成权重更适合)但是要注意的是Mustache(双花括号)语法就不能再次使用。

template

   

 <div id="app">
    <h-title v-cloak level="4">标题</h-title>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    Vue.component('h-title',{
      template : `
          <h1 v-if="level == 1"><slot></slot></h1>
          <h2 v-else-if="level == 2"><slot></slot></h2>
          <h3 v-else-if="level == 3"><slot></slot></h3>
          <h4 v-else-if="level == 4"><slot></slot></h4>
          <h5 v-else-if="level == 5"><slot></slot></h5>
          <h6 v-else-if="level == 6"><slot></slot></h6>
      `,
      props : {
        level : {
          type : String
        }
      }
    })
    let vm = new Vue({
      el : '#app',
    })
  </script>
<!-- 在这种场景中使用 template 并不是最好的选择:首先代码冗长,为了在不同级别的标题中插入锚点元素,我们需要重复地使用 -->

render 

<div id="app">
    <h-title v-cloak :level="4">标题</h-title>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script>
    Vue.component('h-title',{
      render:function(h){
        return h(
          //第一个参数:标签名称
          'h' + this.level,
          //第二个参数:对象:为标签的配置项,添加用于设置这个DOM的一些样式、属性、传的组件的参数、绑定事件等
          {
            //添加自定义属性
            attrs:{
              'data-id' : 10,
            },
            //添加类名
            class:{
              'h-h1' : true 
            },
            //绑定事件
            on: {
                click : this.fn
            },
            //添加样式
               style : {
                '200px',
                height:'200px',
                background:'orange'
            }
          },
          //第三个参数接收内容(类似于插槽)
          this.$slots.default
        )
      },
      props : {
        level : {
          type : String
        }
      },
      methods : {
          fn(){
              console.log('test');
          }
      }
    })
    let vm = new Vue({
      el : '#app',
    })
  </script>
/**
  

  Vue中的Render函数中有一个参数:h,其实这个h叫做createElement。Render函数将createElement的返回值放到了HTML中

  createElement函数的参数解读
      第一个参数(必要参数):主要用于提供DOM的html内容(标签名称),类型可以是字符串、对象或函数
      第二个参数(类型是对象,可选):用于设置这个DOM的一些样式、属性、传的组件的参数、绑定事件等
      第三个参数(类型是数组,数组元素类型是VNode,可选):主要是指该结点下还有其他结点,用于设置分发的内容,包括新增的其他组件。注意,组件树中的所有VNode必须是唯一的. 【用this.$slots.default进行接收】


*/
原文地址:https://www.cnblogs.com/bruce-w/p/13529812.html