gpt4 book ai didi

vue.js - 是否可以在 VueJS 中指定应该在 router.go() 上使用哪个组件

转载 作者:搜寻专家 更新时间:2023-10-30 22:24:24 24 4
gpt4 key购买 nike

在 VueJS 中,我试图设置一个场景,其中使用的组件由 url 路径决定,而无需静态映射它。

例如

router.beforeEach(({ to, next }) => {


FetchService.fetch(api_base+to.path)
.then((response) => {
router.app.$root.page = response

// I'd like to specify a path and component on the fly
// instead of having to map it

router.go({path: to.path, component: response.pageComponent})

})
.catch((err) => {
router.go({name: '404'})
})

})

基本上,我希望能够动态创建路线,而不是在 router.map

中静态指定路径和组件

希望这是有道理的。任何帮助,将不胜感激。

最佳答案

我认为您要归档的是基于当前路由以编程方式加载某些组件。

我不确定这是否是推荐的解决方案,但这是我想到的。

  1. 创建一个 DynamicLoader 组件并将组件作为模板
<template>
<component :is="CurrentComponent" />
</template>
  1. 在 $route 上创建一个 watch 以在每次路由更改时加载新组件
<script>
export default {
data() {
return {
CurrentComponent: undefined
}
},
watch: {
'$route' (to, from) {
let componentName = to.params.ComponentName;
this.CurrentComponent = require(`components/${componentName}`);
}
},
beforeMount() {
let componentName = this.$route.params.ComponentName;
this.CurrentComponent = require(`components/${componentName}`);
}
}
</script>
  1. 在你的路由器上只注册这条路由
{ path: '/:ComponentName', component: DynamicLoader }

在这个例子中,我假设我所有的组件都在 components/ 文件夹中,在你的例子中,你似乎正在调用一个外部服务来获取真正的组件位置,这应该可以工作

如果对你有帮助,请告诉我

关于vue.js - 是否可以在 VueJS 中指定应该在 router.go() 上使用哪个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41028923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com