简体   繁体   中英

Vue.js EventListenner

I'm completely newbie in Vue.js and i've to use it in order to complete a programming task. i'm getting in trouble trying to call pure JS in Vue file. I just have to add an event listener on an element, there is an example:

document.getElementById("mp_addCloud").addEventListener('hover',function(){
alert(1);
})

Can i do it without use v-on in the frontend? Maybe calling an annonymous function? (I wanna do it without any user call action) Thanks

Yes. In the Mounted() hook of the component that contains the element #mp_addCloud , you can say something to the effect of:

this.$el.querySelector('#mp_addCloud').addEventListener(...)

Clarification: in that statement, this is the Vue component. $el is that component's root element.

Edit: as @cccn stated in their answer, the event name is mouseover , not hover .

Edit 2: If you want to use the v-on directive, you can wrap the event in an anonymous function or call a method on the Vue element:

Anonymous function: <my-element v-on:mouseover="() => alert('1')"></my-element>

Via method: <my-element v-on:mouseover="myAlertFunction"></my-element>

With this approach, you'll need to define your method in the Vue component's methods:

methods: {
   myAlertMethod() {
    alert('1');
  }
}

This has nothing to do with Vue. You just use wrong event. Try with mouseover instead of hover .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM