Skip to content
Advertisement

Bind event to multiple objects

I’m trying to attach the same behavior to several different elements and haven’t been able to figure out how.

Given the below snippet of code, if you were to click on the button the events fire for both buttons simultaneously. I’m wondering if it’s possible to trigger the event for only the button that was clicked without resorting to creating methods for button1 and showInside1, etc.

var App = new Vue({
  el: '#app',
  data() {
    return {
        showInside: false
    }
  },
  methods:{
    show: function () {
        this.showInside = true 
    },
    hide: function () { 
        console.log('hide')
        this.showInside = false
    }
  },
  events: {
    closeEvent: function () {
      console.log('close event called')
      this.hide()
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button @click.stop="show">1 Click me</button>
  <div v-if="showInside">
    <p>This is box 1</p>  
    <button @click="hide">Close</button>
  </div>


  <button @click.stop="show">2 Click me</button>
  <div v-if="showInside">
    <p>This is box 2</p>  
    <button @click="hide">Close</button>
  </div>
</div>

Advertisement

Answer

Consider moving the common code to a component with slots to reduce the repetitive code and to isolate the data properties:

Vue.component('my-section', {
  template: `
    <div class="my-section">
      <button @click.stop="showInside = true">Click me</button>
      <div v-if="showInside">
        <slot></slot>
        <button @click="showInside = false">Close</button>
      </div>
    </div>`,
  data() {
    return {
        showInside: false
    }
  },
  methods:{
    show: function () {
        this.showInside = true 
    },
    hide: function () { 
        console.log('hide')
        this.showInside = false
    }
  },
  events: {
    closeEvent: function () {
      console.log('close event called')
      this.hide()
    }
  }
})

var App = new Vue({
  el: '#app',
})
.my-section {
  margin: 1em;
  padding: 0.5em;
  border: solid 1px #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <my-section>
    <p>This is box 1</p>
  </my-section>
  <my-section>
    <p>This is box 2</p>
  </my-section>
</div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement