首页 > 解决方案 > 如何从开槽组件调用方法或向父组件发出事件?

问题描述

这是我的模板

<template>
  <some-component>
    <button>Hello!</button>
  </some-component>
</template>

这是我的组件(一些组件)

<template>
  <slot />
</template>

<script>
export default {
  methods: {
    someMethod() {
      // Does something
    }
  }
}
</script>

我将如何someMethod()从插入组件的按钮调用,或者发出一个some-component可以监听的事件,以从插入的按钮运行方法本身?

标签: javascriptvue.jsvuejs3

解决方案


someMethod您可以作为插槽道具传递some-component

<template>
  <slot :onClick="someMethod" />
</template>

然后使用的父级some-component可以将插槽道具绑定到button

<some-component>
  <template v-slot="{ onClick }">
    <button @click="onClick">Click me</button>
  </template>
</some-component>

演示


推荐阅读