做者:Michael Thiessen
译者:前端小智
来源:medium
点赞再看,微信搜索
【大迁世界】 关注这个没有大厂背景,但有着一股向上积极心态人。本文
GitHub
https://github.com/qq44924588... 上已经收录,文章的已分类,也整理了不少个人文档,和教程资料。
代码部署后可能存在的BUG无法实时知道,过后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给你们推荐一个好用的BUG监控工具 Fundebug。前端
咱们知道使用做用域插槽能够将数据传递到插槽中,可是如何从插槽传回来呢?vue
将一个方法传递到咱们的插槽中,而后在插槽中调用该方法。 我信没法发出事件,由于插槽与父组件共享相同的上下文(或做用域)。git
// 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>
在本文中,咱们将介绍其工做原理,以及:github
如今看一下Parent组件的内容:微信
// Parent.vue <template> <Child> <button @click=""> Click this button </button> </Child> </template>
咱们在 Child
组件的插槽内有一个button
。 单击该按钮时,咱们要在Parent
组件内部调用一个方法。工具
若是 button
不在插槽中,而是直接在Parent
组件的子组件中,则咱们能够访问该组件上的方法:this
// Parent.vue <template> <button @click="handleClick"> Click this button </button> </template>
当该 button
组件位于插槽内时,也是如此:spa
/ Parent.vue <template> <Child> <button @click="handleClick"> Click this button </button> </Child> </template>
之因此可行,是由于该插槽与 Parent
组件共享相同的做用域。debug
模板做用域:模板内部的全部内容均可以访问组件上定义的全部内容。调试
这包括全部元素,全部插槽和全部做用域插槽。
所以,不管该按钮在模板中位于何处,均可以访问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 --> <slot :clicked="handleClick" /> </div> </template>
每当单击按钮时,就会调用Child
组件中的handleClick
方法。
代码部署后可能存在的BUG无法实时知道,过后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给你们推荐一个好用的BUG监控工具 Fundebug。
原文:https://stackoverflow.com/que...
文章每周持续更新,能够微信搜索【大迁世界 】第一时间阅读,回复【福利】有多份前端视频等着你,本文 GitHub https://github.com/qq449245884/xiaozhi 已经收录,欢迎Star。