How to trigger click on ref in Vue.js
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!