I've been struggling with a very odd bug(?) with regards to importing an API module into a nested component in a Vue app.
This is the simplest I could reduce the issue down to. https://codesandbox.io/s/rough-tree-fqj7o
Essentially, the DogsCreate
component renders the CreateDogsModal
, which is importing the dogs
module from the API directory.
As you can see, the codesandbox errors out even on the base URL with the error Cannot read property 'default' of undefined
. If running this code locally not on codesandbox, the base URL renders ok, but if you go to /dogs/create
, the error then becomes Failed to resolve component: CreateDogsModal
.
The things I've found that fix this are:
CreateDogsModal
(not an option for us, we need to be able to create and import API modules)TopNav
component in main.js
(...also not an option for us)TopNav
component in App.vue
with a relative import or @/components/TopNav.vue
works fine, but strangely importing CreateDogsModal
and CreateTemplate
in DogsCreate.vue
with a relative import or @/components/[component-name].vue
does not. Also, the latter would be somewhat acceptable as a long-term solution, but I'd prefer the @/components
shorthand and that still leaves the root cause undetermined. I'm using the default vue-cli
webpack configuration and have checked via vue inspect
that the alias seems to be set properly.
I've been spinning my wheels for a week trying to figure this out and just...cannot. Does anyone have any ideas for what may be happening?
It seems like a race condition in Webpack, using parallel builds, but I'm honestly not sure. I can see CreateDogsModal
being pulled in from two places, starting from main.js
:
'main.js'
- import 'App.vue'
- import '@/components/index.js'
- import and export 'CreateDogsModal.vue'
- import 'router/index.js'
- import '@/views/Dogs/DogsCreate.vue'
- import '@/components/index.js'
- import and export 'CreateDogsModal.vue'
One workaround is to remove the race by making the CreateDogsModal
an async component in DogsCreate
:
// DogsCreate.vue
import { defineAsyncComponent } from "vue";
import { CreateTemplate } from "@/components";
export default {
name: "DogsCreate",
components: {
CreateTemplate,
CreateDogsModal: defineAsyncComponent(() => import("@/components/CreateDogsModal.vue")),
},
};
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.