[Vuejs]-Adding mouse event to dynamic created element Vuejs

1👍

The problem:

Let’s look at the problematic line:

bar.setAttribute("mouseover", this.showBlock(500, false));

I see the following issues:

  • It first calculates the return value of this.showBlock(500, false), then sets it to mouseover attribute. That value is most likely undefined, since your function doesn’t return anything.
  • The value doesn’t even matter, because mouseover attribute has absolutely no meaning in HTML, nor in Vue, which looks for v-on:mouseover or @mouseover.
  • Vue only looks for these attributes/directives when it is initialized, but you are adding the elements after Vue initialization.

Possible solutions:

A) Make sure your Vue model is accessible as a global variable (like window.app), then you can do the trick with onmouseover HTML attribute and stringifying your function call:

bar.setAttribute("onmouseover", "app.showBlock(500, false)");

B) Add an event listener instead of an attribute. Something like this:

bar.addEventListener("mouseover", function () { app.showBlock(500, false); });

This also requires your Vue instance to be accessible.

See a complete solution in @saiyan’s answer.

C) As you are not doing anything that Vue can’t do, you can (and I advise you to) use Vue to create your elements instead. In my opinion, that’s the point of Vue, to ease the pain of creating and modifying elements. Based on your quoted for loop, a Vue implementation would look like this (in your HTML):

<div class="bar">
  <div v-for="i in items" :class="i.colour" :style="{ width: i.weight + '%' }" @mouseover="showBlock(500, false)"></div>
</div>

For a complete solution, please check out @Bert’s fiddle.

1👍

Try this . I made some changes in your jsfiddle code.

for (let i = 0; i < this.items.length; i++) {
        let bar = document.createElement('div');
      bar.className = this.items[i].colour;
      bar.style.cssText = `width: ${this.items[i].weight}%`;
            // ?
     // bar.setAttribute("mouseover", this.showBlock(500, false));
        document.querySelector('.bar').appendChild(bar);



    }
    var that=this;
    setTimeout(function(){
      document.querySelector('.bar').childNodes.forEach(function(e,y){
        e.addEventListener("mouseover", function(){that.showBlock(500, false)});
      });},100);

worked for me in jsfiddle

👤saiyan

Leave a comment