Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bubble up a click event from a custom component in vue.js?

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?

like image 245
Timo Ernst Avatar asked Nov 24 '17 10:11

Timo Ernst


3 Answers

In the child component:

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

And then in the parent component:

<MyButton @click="someFunction"/>
like image 52
Nathan Wailes Avatar answered Nov 11 '22 06:11

Nathan Wailes


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

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

Hope it helps

like image 43
Purvesh Avatar answered Nov 11 '22 06:11

Purvesh


  <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.

like image 5
klimat Avatar answered Nov 11 '22 05:11

klimat