1

I used vue-cli to scaffold a new Typescript project and specified it should include vue-router.

This auto-generated a router/index.ts with a router configuration that looked like this:

const routes: Array<RouteConfig> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
 },
  {
    path: '/about',
    name: 'About',
    component: () => { import(/* webpackChunkName: "about" */ '../views/About.vue') },
  }
]

This file compiles fine as one would expect. However, when I try to call the route using <router-link> the About page does not render. I can confirm the route is being called, because if I add a console.log('x') into the import lambda above, I see the 'x' in the console but the About component constructor is never called and the About content is not rendered.

However, if I adjust the index.ts as follows (as per docs), then the route works correctly and displays the view:

const AboutRoute = () => import('../views/About.vue')

const routes: Array<RouteConfig> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
 },
  {
    path: '/about',
    name: 'About',
    component: AboutRoute,
  }
]

Can anyone explain why the second version works, but not the first as they seem equivalent to me.

Thanks Ian

Ian Ash
  • 1,087
  • 11
  • 23
  • 1
    Does this answer your question? [Curly Brackets in Arrow Functions](https://stackoverflow.com/questions/35440265/curly-brackets-in-arrow-functions) – Phil Jul 20 '20 at 23:40

1 Answers1

2

Your 1st solution doesn't work because it's not returning the import.

In Javscript when you add brackets { } to a function, it's not going to return the result automatically, you need to add the return word yourself. So either don't add brackets or add return:

Method 1:

component: () => {
  return import(
    /* webpackChunkName: "about" */ 
    '../views/About.vue'
  )
}

Method 2:

component: () => import(
  /* webpackChunkName: "about" */ 
  '../views/About.vue'
)
AlekseyHoffman
  • 2,438
  • 1
  • 8
  • 31