从插槽中的内容向父级发出事件 [英] Emit event from content in slot to parent

查看:22
本文介绍了从插槽中的内容向父级发出事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个灵活的轮播控件,允许内部内容元素强制更改幻灯片,以及轮播控件本身来更改幻灯片

我页面中的示例结构如下

<div class="slide"><button @click="$emit('next')">下一步</button>

<div class="slide"><button @click="$emit('close')">关闭</button>

</my-carousel>

我的轮播模板就像

<页脚><!-- 其他轮播控件,如箭头、指示器等放在此处--></页脚>

和脚本一样

<代码>...创建(){this.$on('next', this.next)}...

访问幻灯片等没有问题,但是使用 $emit 不起作用,我似乎无法找到解决此问题的简单方法.

我希望组件易于重用而无需使用

  • 中央事件总线
  • 轮播中的硬编码幻灯片
  • 在页面级别实现下一个幻灯片方法并将当前索引传递给控件(因为我每次使用轮播时都必须这样做)

解决方案

槽是针对父组件作用域编译的,因此从槽发出的事件只会被模板所属的组件接收.

如果你想要轮播和幻灯片之间的交互,你可以使用 作用域插槽代替它允许您从轮播到插槽公开数据和方法.

假设你的轮播组件有 nextclose 方法:

轮播模板:

<页脚><!-- 其他轮播控件,如箭头、指示器等放在此处--></页脚>

轮播示例用法:

<div class="slide"><button @click="scope.next">Next</button>

<div class="slide"><button @click="scope.close">Close</button>

</my-carousel>

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

解决方案

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>

这篇关于从插槽中的内容向父级发出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆