我刚刚开始使用 Vue.js ,发现自己一直在寻求jQuery在某些情况下的帮助.最近,我尝试触发"(或模拟)事件,例如单击或模糊事件,但未成功.
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.
我知道在jQuery中您可以执行以下操作:
I know in jQuery you can do the following:
$('#my-selector').trigger('click');但是如何使用Vue.js实现呢?我想尽可能地摆脱使用jQuery.
But how can this be acheived using Vue.js? I am wanting to move away from using jQuery as much as possible.
以下面的示例为例:
<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>如果我要呼叫 anotherRandomFunciton ,我希望它模拟(或触发)上述click事件.但是,我尝试将此事件(或上例中的 e )从不传递给函数.
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.
Vue.js是否有实现此目的的方法?
Does Vue.js have a method for achieving this?
推荐答案您需要使用v-el来获得对按钮的引用,如下所示:
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>然后,使用您的方法:
function anotherRandomFunction() { var elem = this.$els.myBtn elem.click() }这只是本机DOM点击事件.请参见 v-el文档
It's just a native DOM click event. See v-el Documentation
或者从Vue 2.x开始:
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>因为Vue仅使用和侦听本机DOM事件.您可以使用 Element#dispatchEvent 触发本地DOM事件.像这样:
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.
更多推荐
是否可以使用Vue.js触发事件?
发布评论