最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

vue.js - Lazy Loading Routes with conditions - Stack Overflow

programmeradmin3浏览0评论

My routes.js is:

{...
  path: ":term",
  name: "some-name",
  component: () => import("../path/to/com.vue")
}
...

Question is: How to make smth like this and make it works:

{...
  path: ":term",
  name: "some-name",
  component: (route) => {
    if(route.term === 'spam'){
       return import("../path/to/com1.vue")
    }
    return import("../path/to/com.vue")
  }
}

My routes.js is:

{...
  path: ":term",
  name: "some-name",
  component: () => import("../path/to/com.vue")
}
...

Question is: How to make smth like this and make it works:

{...
  path: ":term",
  name: "some-name",
  component: (route) => {
    if(route.term === 'spam'){
       return import("../path/to/com1.vue")
    }
    return import("../path/to/com.vue")
  }
}
Share Improve this question asked Mar 11 at 11:03 Max SMax S 1311 silver badge5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

The component in a route is only evaluated once. In other words, what you are asking for is not possible, by design.

However, the functionality can be achieved using a dynamic loader component:

<!-- RouteTermLoader.vue -->

<script setup>
import { defineAsyncComponent } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()

const ComponentA = defineAsyncComponent(() =>
  import('./path/to/ComponentA.vue')
)

const ComponentB = defineAsyncComponent(() => 
  import('./path/to/ComponentB.vue')
)
</script>
<template>
  <ComponentA v-if="route.params.term === 'spam'" />
  <ComponentB v-else />
</template>
{
  path: ":term",
  name: "some-name",
  component: () => import("../path/to/RouteTermLoader.vue")
}

Relevant documentation here.

发布评论

评论列表(0)

  1. 暂无评论