2

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

:class="`card-${menu.name}`"

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; });     
},

3
  • hey mate, can you add little more context to your question? It's not clear enough , at least for me, what you are truing to achieve. Commented Oct 8, 2022 at 7:52
  • mounted() { document.querySelector('.card-alpha').addEventListener('click', () => { this.$state.val = 1; }); document.querySelector('.card-beta').addEventListener('click', () => { this.$state.val = 2; }); }, this is inside mounted function. How should I trigger it everytime the button is clicked? Commented Oct 8, 2022 at 7:54
  • Please use the "Edit" link (just below the tags to your question) to add code to the question, where it can be formatted and readable, and also permanent (since comments are transitory). Commented Oct 8, 2022 at 8:32

1 Answer 1

2

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 :class="`card-${menu.name}`" @click="myFunc(menu.val)">
      {{ menu.id }}
    </button>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

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.