如何在vue jsx中使用模板范围?

Jso*_*ong 8 jsx vue.js vuejs2

我定义了一个简单的子组件(testSlot.vue),如下所示:

<template>
    <section>
        <div>this is title</div>
        <slot text="hello from child slot"></slot>
    </section>
</template>
<script>
    export default {}
</script>
Run Code Online (Sandbox Code Playgroud)

我们可以在这样的html模板中使用它

<test-slot>
    <template scope="props">
        <div> {{props.text}}</div>
        <div> this is real body</div>
    </template>
</test-slot>
Run Code Online (Sandbox Code Playgroud)

但我如何在jsx中使用它?

Jso*_*ong 10

在阅读了三次文档后,我现在可以自己回答问题O(∩_∩)O.

<test-slot scopedSlots={
    {
        default: function (props) {
            return [<div>{props.text}</div>,<div>this is real body</div>]
        }
    }}>
</test-slot>
Run Code Online (Sandbox Code Playgroud)

插槽名称是默认值.

所以.我们可以访问scopedSlots.default中的范围(= vm.$ scopedSlots.default)

回调参数'props'是道具的持有者.

并且返回值是vNode,你用子组件公开的范围来表示.

我意识到jsx只是render函数的一个语法糖,它仍然使用createElement函数来创建vNode树.

  • 请注意,对于默认插槽,您现在可以使用:`&lt;test-slot&gt;{(props) =&gt; &lt;div&gt; {props.text}&lt;/div&gt;}&lt;/test-slot&gt;` (2认同)