render 函数(二)

this.$slots 在 render 函数中的应用

 

灌篮高手

我是要成为海贼王的男人

我是h1

《海贼王》

// 用 slot 给 h3起个名字
《火影忍者》

从上例可以看出,在 render 函数中可以不使用 slot 元素,而是直接使用 this.$slots 访问到相应的元素。注意,h3 和 h5 标签中的 slot 是属性,用来给元素“起个名字”的,不是元素!


    console.log(Array.isArray(header))  // true
    console.log(Array.isArray(footer))  // true
    console.log(Array.isArray(main))    // true

由上可得,header、main、footer 都是数组。

这些数组中,存的是 VNode(虚拟节点),也就是 中的节点。
console.log(header)


createElement 的第三个参数,存的就是 VNode(虚拟节点)。

在 render 函数中使用 props 传递数据

在 render 函数中,父组件给子组件传递数据的步骤:
在父组件绑定数据;
在子组件使用 props 接收数据;
在子组件使用接收到的数据。

    
{{show}}

点击切换


在 render 函数中使用 v-­model

在 render 函数中使用 v-model 绑定父组件中的数据;

  • 在父组件中使用 v-model 绑定父组件中的数据;
  • 在子组件中使用 $emit() 触发 input 事件,并传递子组件中的数据。
    

{{name}}

在render函数中使用作用域插槽

作用域插槽使得父组件可以从子组件中获取数据。

Vue.component('child-component', { render: function (createElement) { return createElement('div', this.$scopedSlots.default({ // 使用 this.$scopedSlots.default 定义子组件中的数据 text: '我是子组件中的内容' })) } }) var app = new Vue({ el: '#app', data: { }, })`

函数化组件

函数化组件在实际开发中并不常用。

    

可以从中找到需要的 API 。如:打印出父组件 data 中的数据:

    render: function (createElement, context) {
        return createElement('button', {
            on: {
                click: function () {

                    var a = this
                    console.log(context)
                    console.log(context.parent)
                    // alert(context.parent.msg)
                    // console.log(context.props.value)
                    alert(this.value) //undefined
                }
            }
        }, '点击我学习context')
    }

        var app = new Vue({
            el: '#app',
            data: {
                msg: '父组件内容'
            }
        })

上面代码中的 context.parent 可以访问到父组件。

你可能感兴趣的:(render 函数(二))