Emit event from content in slot to parent(从插槽中的内容向父级发送事件)
问题描述
I'm trying to build a flexible carousel control that allows inner content elements to force changing a slide, aswell as the carousel controls itself to change slides
A sample structure in my page looks like
<my-carousel>
<div class="slide">
<button @click="$emit('next')">Next</button>
</div>
<div class="slide">
<button @click="$emit('close')">Close</button>
</div>
</my-carousel>
The template for my carousel is like
<div class="carousel">
<div class="slides" ref="slides">
<slot></slot>
</div>
<footer>
<!-- other carousel controls like arrows, indicators etc go here -->
</footer>
</div>
And script like
...
created() {
this.$on('next', this.next)
}
...
Accessing the slides etc is no problem, however using $emit
will not work and I can't seem to find a simple solution for this problem.
I want to component to be easily reusable without having to use
- central event bus
- hardcoded slides within a carousel
- implement the next slide methods on page level and pass the current index to the control (as I'd have to do this every time I use the carousel)
Slots are compiled against the parent component scope, therefore events you emit from the slot will only be received by the component the template belongs to.
If you want interaction between the carousel and slides, you can use a scoped slot instead which allows you to expose data and methods from the carousel to the slot.
Assuming your carousel component has next
and close
methods:
Carousel template:
<div class="carousel">
<div class="slides" ref="slides">
<slot :next="next" :close="close"></slot>
</div>
<footer>
<!-- Other carousel controls like arrows, indicators etc go here -->
</footer>
</div>
Carousel example usage:
<my-carousel v-slot="scope">
<div class="slide">
<button @click="scope.next">Next</button>
</div>
<div class="slide">
<button @click="scope.close">Close</button>
</div>
</my-carousel>
这篇关于从插槽中的内容向父级发送事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从插槽中的内容向父级发送事件
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01