1

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 :)

1

2 Answers 2

1

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?

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

2 Comments

Hey thank's for advice. I'm trying to add a popup to a marker in Leaflet. I know there is a VUE Leaflet but can't use it in this case. So the code is L.marker(...).bindPopup('<div onclick="function"></div>');
0

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

3 Comments

Oh sorry but It was only a sample method.
Try out some of vue's built in functionality for dynamic addition / removal of elements to the dom. <div v-if="someBoolean" @click="someFunction"></div>
Try moving the myID to created instead on data.

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.