11

I have a custom component <item> which looks like this:

item.vue

<script>
  export default {
    render: function (c) {
      var self = this;
      const contentEl = c('div', {staticClass:'item-content', domProps: {innerHTML: self.content}});
      return c('div', {
        staticClass: 'item',
        class: {
          'item-left': self.side === 'left',
          'item-right': self.side === 'right'
        }
      }, [contentEl])
    },
    props: {
      content: String,
    }
  }
</script>

It can be used like this:

<item :content="Hello world"></item>

This will print "Hello world" and works fine but now I want the item to be clickable like this:

<item v-on:click="myClickEvent" :content="Hello world"></item>

Question:

How can I make the <item> component to fire a click event when its inner <div> was clicked?

1
  • I finally got your issue, made a couple of edits... should be fine now :) Commented Nov 24, 2017 at 12:12

3 Answers 3

10

In the child component:

<button @click="$emit('click')"></button>

And then in the parent component:

<MyButton @click="someFunction"/>
Sign up to request clarification or add additional context in comments.

Comments

5
  <template>
    <div id="action-button">
      <input type="button" id="in" @click="clicked" :value="value" />    
    </div>
  </template>

  <script>
  export default {
    name: 'action-button',
    props: {
      'value': String
    },
    methods: {
      clicked () {
        this.$emit('action-button-clicked')
      }
    }
  }
  </script>

And then instead of v-on:click you should use v-on:action-button-clicked="handleClick".

<action-button v-on:action-button-clicked="handleClick"></action-button>

So the general idea is to handle clicks internally and then use emit inside your component.

3 Comments

You can read more here vuejs.org/v2/guide/…
@Timo I'm glad I could help. Please upvote the answer as well :)
shorthand: <button @click="$emit('click')"></button> parent: <CuttomButton @click="myFn"/>
4

In the child component you can simply do it as @Nathan said.

<button @click="$emit('click', $event)">My button component</button>

Hope it helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.