【问题标题】:How to call method or emit event to parent component from a slotted component?如何从开槽组件调用方法或向父组件发出事件?
【发布时间】:2021-06-30 20:40:15
【问题描述】:

这是我的模板

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

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

<template>
  <slot />
</template>

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

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

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

    您可以将someMethod 作为some-component 的插槽属性传递:

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

    那么使用some-component的父级可以将slot prop绑定到button

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

    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-06
      • 2021-02-12
      • 2021-07-26
      • 2018-09-30
      • 2018-06-06
      • 2019-08-04
      • 2018-09-30
      • 2021-05-02
      相关资源
      最近更新 更多