0

I was just wondering have anyone tried doing something like this(this is within a vuejs created method):

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)); //not working
    document.querySelector('.bar').appendChild(bar);
}

https://jsfiddle.net/phfilly/eywraw8t/167799/

I’m trying to add a hover mouse event(line 32) to the newly created element. Is there another way to achieve something like this?

4

2 回答 2

1

尝试这个 。我对您的 jsfiddle 代码进行了一些更改。

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

在 jsfiddle 为我工作

于 2018-07-13T14:03:35.200 回答
1

问题:

让我们看看有问题的行:

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

我看到以下问题:

  • 它首先计算 的返回值this.showBlock(500, false)然后将其设置为mouseover属性。该值很可能是undefined,因为您的函数不返回任何内容。
  • 该值甚至无关紧要,因为mouseover属性在 HTML 中绝对没有意义,在寻找v-on:mouseoveror的 Vue 中也没有@mouseover
  • Vue 仅在初始化时查找这些属性/指令,但您是在Vue 初始化之后添加元素。

可能的解决方案:

A)确保您的 Vue 模型可作为全局变量(如window.app)访问,然后您可以使用onmouseoverHTML 属性和字符串化您的函数调用来实现这一点:

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

B)添加事件侦听器而不是属性。像这样的东西:

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

这也要求你的 Vue 实例是可访问的。

在@saiyan 的回答中查看完整的解决方案。

C)由于你没有做任何 Vue 不能做的事情,你可以(我建议你)使用 Vue 来创建你的元素。在我看来,这就是 Vue 的意义所在,可以减轻创建和修改元素的痛苦。根据您引用的for循环,Vue 实现将如下所示(在您的 HTML 中):

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

如需完整的解决方案,请查看@Bert's fiddle

于 2018-07-13T20:53:48.040 回答