使用for循环创建异步Vue组件

时间:2017-05-08 20:34:00

标签: webpack vue.js

我的src文件夹类似于以下树,可以在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

所以我试图创建异步vue组件的数组(blog_post_components)(post0.vue,post1.vue,post2.vue),以便我以后可以使用它们。但是,如果我使用for循环创建blog_post_components,编译的网站将出错。另一方面,如果我只是简单列出所有这些,网站正在按预期工作。

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
})

为什么这段代码不起作用?我真的很感激答案。

// THIS IS NOT WORKING AS INTENDED

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

1 个答案:

答案 0 :(得分:2)

import是一个异步操作。您可能要求../components/blogpost/post3三次,因为var i被提升到范围的顶部,并且当函数实际执行时,i == 3。尝试更改循环以使用let,以便将i限定为循环内部。

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