渲染函数

本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2021-04-15

渲染函数API的改变

渲染函数参数

// 2.x
export default {
  render(h) {
    return h('div')
  }
}

// 3.x
// h(即createElement的别称)函数是全局导入,而不是作为参数自动传递
import { h, reactive } from 'vue';

export default {
  setup(props, { slots, attrs, emit }) {
    // 由于 render函数不再接受参数,它将主要用于 `setup` 函数内部
    // 同时它可以访问在作用域中声明的响应式状态和函数
    const state = reactive({
      count: 0
    })

    render() {
      return h('div', {}, state.count)
    }
  }
}

VNode Prop 格式化

在 3.x 中 VNode prop 的结构都是扁平的。

// 2.x
var prop2 ={
  staticClass: 'button',
  class: { 'is-outlined': isOutlined },
  staticStyle: { color: '#34495E' },
  style: { backgroundColor: buttonColor },
  attrs: { id: 'submit' },
  domProps: { innerHTML: '' },
  on: { click: submitForm },
  key: 'submit-button'
}

// 3.x 语法 更加扁平化,减少嵌套
var prop3 = {
  class: ['button', { 'is-outlined': isOutlined }],
  style: [{ color: '#34495E' }, { backgroundColor: buttonColor }],
  id: 'submit',
  innerHTML: '',
  onClick: submitForm,
  key: 'submit-button'
}

注册组件

// 2.x
Vue.component('button-counter', {
  data() {
    return {
      count: 0
    }
  }
  template: `
    <button @click="count++">
      Clicked {{ count }} times.
    </button>
  `
})

export default {
  render(h) {
    return h('button-counter')
  }
}

// 3.x 由于 VNode 是上下文无关的,不能再用字符串 ID 隐式查找已注册组件。相反地,需要使用一个导入的 resolveComponent 方法:
import { h, resolveComponent } from 'vue'

export default {
  setup() {
    const ButtonCounter = resolveComponent('button-counter')
    return () => h(ButtonCounter)
  }
}

插槽统一

// 2.x 语法
h(LayoutComponent, [
  h('div', { slot: 'header' }, this.header),
  h('div', { slot: 'content' }, this.content)
])
// 引用
this.$scopedSlots.header

// 3.x 语法,将插槽定义为当前节点的子对象
h(LayoutComponent, {}, {
  header: () => h('div', this.header),
  content: () => h('div', this.content)
})
// 引用 这里是函数 需要直接调用
this.$slots.header()

需要做的改动即:

  • 在 3.x 中,将所有 this.$scopedSlots 替换为 this.$slots,并将插槽作为函数公开。

  • 将所有 this.$slots.mySlot 替换为 this.$slots.mySlot()

移除 $listeners

$listeners 对象在 Vue 3 中已被移除。现在事件监听器是 $attrs 的一部分,即事件监听器现在只是以 on 为前缀的 attribute

var attrs = {
  text: 'this is an attribute',
  onClose: () => console.log('close Event triggered')
}

$attrs包括class&style

在 Vue 2 的虚拟 DOM 实现中对 class 和 style attribute 有一些特殊处理。因此,它们不包括在 $attrs 中,而其它所有 attribute 都在。现在 $attrs 包含传递给组件的所有 attribute,包括 class 和 style。 了解更多 $attrs 的改动