Reputation: 1130
I have a simple button component that is asynchronously loaded into another component.
I have a call in mounted that references the button component but I get an error the it is undefined. If I import the button as you normally would there are no issues. I am attempting to load as asynchronously as I have other points where I would call the button however in this case it should be ready to go on mounted.
It was my understanding that vue will load the component when you need it however I need it on mounted but can not access it. Am OI going about this wrong? Maybe I don't completely understand it all yet.
**error**
Error in v-on handler: "TypeError: Cannot read property '$el' of undefined"
**code**
<template>
<div class"wrapper">
<button ref="flipBtn" /> I am the text </button>
</div>
</template>
// Works if I import this way
// import button from '@/components/inline-components/button'
export default {
components: {
// button
button: () => { import ('@/components/inline-components/button') }
},
mounted() {
// I have tried wrapping in a this.$nextTick(() => {}) but no luck
this.$refs.flipBtn.$el.focus({ preventScroll: true })
}
}
Upvotes: 1
Views: 2698
Reputation: 1130
Thanks to @HusamIbrahim suggestions I was able to get rid of the error by using both a custom directive and a conditional check of the $refs in a later function call
**error**
Error in v-on handler: "TypeError: Cannot read property '$el' of undefined"
**code**
<template>
<div class"wrapper">
<button ref="flipBtn" v-focus /> I am the text </button>
</div>
</template>
// Works if I import this way
// import button from '@/components/inline-components/button'
export default {
components: {
// button
button: () => { import ('@/components/inline-components/button') }
},
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
}
methods {
// Wasn't apart of my original question but I was able to remove the error on it using comments above.
glideAfter () {
// Give Flip button focus, Hidden button that helps with keyboard focus
if (this.$refs && this.$refs.flipBtn) {
this.$refs.flipBtn.$el.focus({ preventScroll: true })
}
}
}
Upvotes: 0