最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - addEventListener inside Vue-Component with vanilla JS - Stack Overflow

programmeradmin4浏览0评论

It seems that vanilla eventListeners don't work when referencing dom-objects inside vue-ponents.

Markup

<p id="test1">Hover this (works)</p>
<div id="app">
    <p id="test2">Hover this (not working)</p>
</div>

JS

document.querySelector('#test1').addEventListener('mouseover', function() {
    alert("HOVER1")
})

document.querySelector('#test2').addEventListener('mouseover', function() {
    alert("HOVER2")
})

new Vue({
    el: "#app"
})

Live-Example

/

Is this behaviour intended? Are there any other limitations when bining vanilla-js with vue?

It seems that vanilla eventListeners don't work when referencing dom-objects inside vue-ponents.

Markup

<p id="test1">Hover this (works)</p>
<div id="app">
    <p id="test2">Hover this (not working)</p>
</div>

JS

document.querySelector('#test1').addEventListener('mouseover', function() {
    alert("HOVER1")
})

document.querySelector('#test2').addEventListener('mouseover', function() {
    alert("HOVER2")
})

new Vue({
    el: "#app"
})

Live-Example

https://jsfiddle/seltsam23/dq7euos0/

Is this behaviour intended? Are there any other limitations when bining vanilla-js with vue?

Share Improve this question edited Sep 27, 2018 at 10:12 Seltsam asked Sep 27, 2018 at 9:54 SeltsamSeltsam 9441 gold badge8 silver badges28 bronze badges 2
  • What are the output ? That when you hover on the "hover this" it pops a window and when ou click on the "click" it pops a window ? (according to the jsfiddle) – LPK Commented Sep 27, 2018 at 10:02
  • 1 Oh well, that was an old version of that fiddle. Just updated the link to match the description again. Thank you – Seltsam Commented Sep 27, 2018 at 10:13
Add a ment  | 

1 Answer 1

Reset to default 10

Actually, the only one that is not working is the example with alert("HOVER2") and it's because Vue content is dynamically rendered, so when your script loads, the element to which you want to add the event listener might not be there yet.

If you want it to work, you would need to move it to mounted hook:

new Vue({
  el: "#app",
  mounted() {
    document.querySelector('#test2').addEventListener('click', function() { alert("HOVER2") })
  }
})

Or you could use a little trick by putting your querySelector inside of setTimeout(() => ..., 0) which will push it to the end of the task queue and run it when all other queued tasks are finished:

setTimeout(() => document.querySelector('#test2').addEventListener('click', function() { alert("HOVER2") }), 0);

However, you should use Vue's built-in events and avoid doing direct DOM manipulations, because Vue discards whatever you've done to DOM and updates it with it's virtual DOM on next update tick. In this case it doesn't result in anything critical, but since Vue has it's own event handlers, you should use them.

发布评论

评论列表(0)

  1. 暂无评论