Use for loop to create async Vue component

My src folder looks like the following tree and playback can be found at https://github.com/vwxyzjn/loop_async_import

|   App.vue
|   main.js
|
+---assets
|       logo.png
|
+---components
|   |   Hello.vue
|   |
|   \---blogpost
|           post0.vue
|           post1.vue
|           post2.vue
|
\---router
        index.js

      

So I'm trying to create an array (blog_post_components) of vue async components (post0.vue, post1.vue, post2.vue) so I can use them later. But if I use a for loop to create blog_post_components objects, the compiled website has an error. On the other hand, if I just list them all, the site is working as intended.

import Vue from 'vue'
import Router from 'vue-router'
import Hello from '../components/Hello'

var blog_post_components = []

// THIS IS NOT WORKING AS INTENDED
// Error information: (unknown) Error: Cannot find module './post3'.

for (var i = 0; i < 3; i++){
  blog_post_components.push(() => ({
    component: import('../components/blogpost/post' + i)
  }))
}


// THIS IS WORKING AS INTENDED, ALMOST THE SAME AS THE FOR LOOP ABOVE

// blog_post_components.push(() => ({
//   component: import('../components/blogpost/post' + 0)
// }))
// blog_post_components.push(() => ({
//   component: import('../components/blogpost/post' + 1)
// }))
// blog_post_components.push(() => ({
//   component: import('../components/blogpost/post' + 2)
// })



console.log(blog_post_components)

var routes = [
  {path: '/', component: Hello}
]
for (var j = 0; j < 3; j++){
  routes.push({path: '/post/' + j, component: blog_post_components[j]})
}
console.log(routes)

Vue.use(Router)
export default new Router({
  mode: 'history',
  base: __dirname,
  routes: routes
})

      

Why doesn't this code work? I will be very grateful for your answer.

// THIS IS NOT WORKING AS INTENDED

for (var i = 0; i < 2; i++){
  blog_post_components.push(() => ({
    component: import('../components/blogpost/post' + i)
  }))
}

      

+3


source to share


1 answer


import

- asynchronous operation. Probably you ask ../components/blogpost/post3

three times, because it var i

rises to the top of the field of action, and when the function is actually performed i == 3

. Try changing your loop to use let

to i

be tied to the inside of the loop.



for (let i = 0; i < 2; i++){
  blog_post_components.push(() => ({
    component: import('../components/blogpost/post' + i)
  }))
}

      

+2


source







All Articles