I have a list
<li v-for="menu_item, key in menu" @click="clickMenu(key)" :ref="'menu'+key">
{{menu_item.name}}
</li>
And in my vue I have
mounted(){
// This shows the $refs as being mounted and available
console.log(this.$refs)
console.log(this.$refs.menu1)
// Click menu item 2 seconds after mounting
this.$refs.menu1.click()
// click is UNDEFINED
},
methods: {
clickMenu:function(key){
console.log("CLICKED "+key)
},
}
I get "Cannot read property 'click' of undefined"
How do I simply just trigger a click on the element programmatically?
Another answer on Github says I should do ...
this.$refs.menu1.$el.click()
But that isn't defined either ??
Heres a JSFiddle Hopefully someone can figure it out JSFIDDLE HERE!!
There may a couple of small issues with your code. The context of this
inside setTimeout()
when using function() {}
is not what you are expecting. To preserve the context of this
to be able to access $refs
and similar component properties/functions, use an arrow function instead () => {}
.
The next issue is accessing the underlying element of a ref such as menu1
. I've provided an example below, but logging this.$refs.menu1
returns an array of elements [<li>]
. You would need to do something along the lines of this.$refs.menu1[0]
to access the underlying element (there be a more "Vue" way of doing this though):
{
// ...
methods: {
handleClick(key) {
console.log(key);
}
},
mounted() {
console.log(this.$refs);
console.log(this.$refs.menu1[0]);
console.log(this);
setTimeout(() => {
console.log(this);
this.$refs.menu1[0].click();
}, 2000);
}
}
Here is an example in action.
Hopefully that helps!
如果您的目标是单击菜单的第一项,只需调用 clickMenu 方法并发送索引,在这种情况下,它将是 clickMenu(0)。
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.