Warm tip: This article is reproduced from stackoverflow.com, please click
jsx vue.js

How add click events to Vue slots?

发布于 2020-03-29 21:00:17

The parent element:

<solt-div>
  <button slot="trigger">选取文件</button>
</solt-div>

The slot component :

export default {
  render () {
      return(<div>{this.$slots.trigger}</div>)
  }
}

I need to add a click event to this.$slots.trigger in order to trigger a function in the solt-div component

But this event cannot be added to the outer DIV, because there are other slots

<trigger @click="fn"></trigger>
Questioner
ebyte ebyte
Viewed
40
Troy Kessler 2020-01-31 18:25

After some trying to add an event in the render function with createElement I came to the solution where you can use a reference to call your function in solt-div

Parent

<solt-div ref="soltDiv">
    <button slot="trigger" @click="$refs.soltDiv.fn()">test</button>
</solt-div>

solt-div

export default {
  render () {
      return(<div>{this.$slots.trigger}</div>)
  },
  methods: {
    fn() {
      // do stuff
    }
  }
},