我有一个简单的按钮组件,该组件被异步加载到另一个组件中。
我在挂接中引用了按钮组件的调用,但是我收到一个错误消息,它是未定义的。如果我像平常一样导入按钮,就不会有问题。我正在尝试像其他地方一样异步加载按钮,但是在这种情况下,应该可以继续安装了。
据我了解,vue会在您需要时加载该组件,但是我需要将其挂载但无法访问。 OI会为这个错误做准备吗?也许我还不完全了解这一切。
**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 })
}
}
答案 0 :(得分:0)
由于@HusamIbrahim的建议,我可以通过在以后的函数调用中同时使用自定义指令和$ refs的条件检查来摆脱错误
**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 })
}
}
}