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!!
To trigger the Vue watch method, you should assign a new city name to the value property of the ref object.
With Vue, you can tie button clicks to functions you want to execute. The formal way to do this is to use the v-on:click attribute, however, Vue has a neat shortcut, @click .
They allow us to access or modify the DOM of your component just before or after the first render. So, here we will use the mounted hook to trigger a click event when the page is loaded. Step-1: Give a reference to the button you want to click. Step-2: In the mounted hook trigger the button click.
$refs...are not reactive. However, I have used such refs in templates and they are indeed reactive, and even in methods, computed props, and watchers (as long as you access it after being mounted). Several third party vue libraries e.g. this one also provides features that use/depend on the reactivity of refs.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With