Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - Is it possible to trigger events using Vue.js?

I have just started using Vue.js and find myself continuously turning to jQuery to help in certain situations. Most recently I have attempted to, unsuccessfully "trigger" (or emulate) an event, such as an on click or blur event.

I know in jQuery you can do the following:

$('#my-selector').trigger('click');

But how can this be acheived using Vue.js? I am wanting to move away from using jQuery as much as possible.

Take the below as an example:

<div id="my-scope">
    <button type="button" v-on="click: myClickEvent">Click Me!</button>
</div>

<script>
new Vue({
    el: "#my-scope",
    data: {
        foo: "Hello World"
    },
    methods: {
        myClickEvent: function(e) {
            console.log(e.targetVM);
            alert(this.foo);
        },
        anotherRandomFunciton: function() {
            this.myClickEvent();
        }
    }
});
</script>

If I was to call anotherRandomFunciton, I would like it to emulate (or trigger) the above click event. However, I attempt this the event (or e in the above example) never gets passed to the function.

Does Vue.js have a method for achieving this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to get a reference to your button by using v-el like so:

<button type="button" @click="myClickEvent" v-el:my-btn>Click Me!</button>

Then, in your method:

function anotherRandomFunction() {
    var elem = this.$els.myBtn
    elem.click()
}

It's just a native DOM click event. See v-el Documentation

Or since Vue 2.x:

<template>
    <button type="button" @click="myClickEvent" ref="myBtn">
        Click Me!
    </button>
</template>

<script>
export default {
    methods: {
        myClickEvent($event) {
            const elem = this.$refs.myBtn
            elem.click()
        }
    }
}
</script>

Since Vue uses and listens for native DOM events only. You can trigger native DOM events using the Element#dispatchEvent like so:

var elem = this.$els.myBtn; // Element to fire on

var prevented = elem.dispatchEvent(new Event("change")); // Fire event

if (prevented) {} // A handler used event.preventDefault();

This is not exactly ideal or best practice. Ideally, you should have a function that handles the internals and an event handler that calls that function. That way, you can call the internals whenever you need to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...