我们知道使用作用域插槽可以将数据传递到插槽中,但是如何从插槽传回来呢?
将一个方法传递到我们的插槽中,然后在插槽中调用该方法。 我信无法发出事件,因为插槽与父组件共享相同的上下文(或作用域)。
// Parent.vue <template> <Child> <template #default="{ clicked }"> <button @click="clicked"> Click this button </button> </template> </Child> </template>
// Child.vue <template> <div> <!-- 将“handleClick” 作为 “clicked” 传递到我们的 slot --> <slot :clicked="handleClick" /> </div> </template>
在本文中,我们将介绍其工作原理,以及:
- 从插槽到父级的 emit
- 当一个槽与父组件共享作用域时意味着什么
- 从插槽到祖父组件的 emit
- 更深入地了解如何使用方法从插槽通讯回来
从插槽到父级的 emit
现在看一下Parent组件的内容:
// Parent.vue <template> <Child> <button @click=""> Click this button </button> </Child> </template>
我们在 Child
组件的插槽内有一个button
。 单击该按钮时,我们要在Parent
组件内部调用一个方法。
如果 button
不在插槽中,而是直接在Parent
组件的子组件中,则我们可以访问该组件上的方法:
// Parent.vue <template> <button @click="handleClick"> Click this button </button> </template>
当该 button
组件位于插槽内时,也是如此:
/ Parent.vue <template> <Child> <button @click="handleClick"> Click this button </button> </Child> </template>
之所以可行,是因为该插槽与 Parent
组件共享相同的作用域。
插槽和模板作用域
模板作用域:模板内部的所有内容都可以访问组件上定义的所有内容。
这包括所有元素,所有插槽和所有作用域插槽。
因此,无论该按钮在模板中位于何处,都可以访问handleClick
方法。
乍一看,这可能有点奇怪,这也是为什么插槽很难理解的原因之一。插槽最终渲染为Child
组件的子组件,但它不与Child
组件共享作用域。相反,它充当Parent
组件的子组件。
插槽向祖父组件发送数据
如果要从插槽把数据发送到祖父组件,常规的方式是使用的$emit
方法:
// Parent.vue <template> <Child> <button @click="$emit('click')"> Click this button </button> </Child> </template>
因为该插槽与Parent
组件共享相同的模板作用域,所以在此处调用$emit
将从Parent
组件发出事件。
从插槽发回子组件
与Child
组件通讯又如何呢?
我们知道如何将数据从子节点传递到槽中
// Child.vue <template> <div> <slot :data="data" /> </div> </template>
以及如何在作用域内的插槽中使用它:
// Parent.vue <template> <Child> <template #default="{ data }"> {{ data }} </template> </Child> </template>
除了传递数据,我们还可以将方法传递到作用域插槽中。 如果我们以正确的方式连接这些方法,则可以使用它来与Child
组件通信:
// Parent.vue <template> <Child> <template #default="{ clicked }"> <button @click="clicked"> Click this button </button> </template> </Child> </template>
// Child.vue <template> <div> <!-- Pass `handleClick` as `clicked` into our slot --> <em style="color:transparent">本文来源[email protected]搞@^&代*@码)网9</em> <slot :clicked="handleClick" /> </div> </template>
每当单击按钮时,就会调用Child
组件中的handleClick
方法。
原文地址:https://stackoverflow.com/questions/50942544/emit-event-from-content-in-slot-to-parent/50943093
作者:Michael Thiessen
转载自:https://segmentfault.com/a/1190000023373867
译者:前端小智
想要了解更多前端的相关知识,可访问 web前端学习!!
以上就是Vue从插槽中发出数据的方法介绍的详细内容,更多请关注gaodaima搞代码网其它相关文章!