Home > Software design >  Add event listener vuejs
Add event listener vuejs

Time:10-08

Hello I am working with Vuejs. I am assigning class names dynamically based on my project requirement, in a loop

:

Where menu.name can be alpha, beta,zeta etc.

Now I want to add event listener to each class differently like do a1 when click on class card-alpha, do a2 when click on class card-beta and so on. Please see that I cannot use @click="myfunc" since I want different things to be done on each different class, so its something else. Can you help me with this. Thanks a lot

Here is the code which I am using and which wont work as it only runs once when the code is mounted. So how to trigger this function everytime on click?

mounted() {       
    document.querySelector('.card-alpha').addEventListener('click', () => { this.$state.val = 1; });       
    document.querySelector('.card-beta').addEventListener('click', () => { this.$state.val = 2; });     
},

CodePudding user response:

You can pass value to your function, without listeners in mounted hook:

const app = Vue.createApp({
  data() {
    return {
      items: [{id:1, name: 'alpha', val: 1}, {id:2, name: 'beta', val: 2}],
    };
  },
  methods: {
    myFunc(val) {
      // do other things
      // set your state with passed value
      //this.$state.val = val
      alert(val)
    }
  }
})
app.mount('#demo')
.card-beta {
  color: red;
}
.card-alpha {
  color: green;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="menu in items" :key="menu.id">
    <button : @click="myFunc(menu.val)">
      {{ menu.id }}
    </button>
  </div>
</div>

  • Related