Home > Back-end >  VUE add onclick event to dynamically created element
VUE add onclick event to dynamically created element

Time:12-22

I'm trying to add @click event to dynamically created element. My code is:

const app = Vue.createApp({
 data() {
  return {
   myID: 24,
  };
 },

 ...

 methods: {
  mymethod(ID) {
   ...
 },
  otherFunction() {
   ...
   dom.innerHTML  = `<div onclick="mymethod(${this.myID})"></div>`;
  }
});

So after clicking at div the console says 'alert is not defined'. My question is how to target this method or is there a better way of creating element dynamically?

Thank you :)

CodePudding user response:

Try this out. <div onclick="window.alert(${this.myID})"></div>

CodePudding user response:

Do not mutate DOM directly!

This is really, really important for FE frameworks like Vue. While mutating the DOM directly is possible, it's going to cause all kinds of problems.

Before addressing how to add an onclick listener, you should consider what your goal is and then pick the solution for your needs.

Most likely you can solve this within the template syntax. If not, you can also use JSX or render functions. If there is a particular reason why you need to include something like dom.innerHTML, can you include it in the question?

  • Related