【问题标题】:Importing and Exporting variables in vue js在 vue js 中导入和导出变量
【发布时间】:2021-04-25 02:54:21
【问题描述】:

有什么方法可以将这个 routes 变量 导入另一个文件。注意我导入路由器只是路由变量。 下面的代码是我试图做的

src/router.js

const routes = [
{
    path:"/",
    name:"home",
    component: HomeTemplate
},
{
    path:"/heroes",
    name:"heroes",
    component: /*webpackChunkName: Heroes*/ import("@/components/DcHeroes/DcHeroes")
},
{
    path:"/calendar",
    name:"calendar",
    component: /*webpackChunkName: Calendar*/ import("@/components/CalendarTemplate")
},
{
    path:"/markdown",
    name:"markdown",
    component: /*webpackChunkName: Markdown*/ import("@/components/MarkDownTemplate")
},
]
const router = createRouter({
    history:createWebHistory(),
    routes,
    base:'/'
})
export default router;

src/components/navbar/index.vue

<template>
    <div>
        <h2>Navbar</h2>
        <router-link :to="{ name:'home', }">Home</router-link>
        <router-link :to="{ name:'heroes', }">Heroes</router-link>
        <router-link :to="{ name:'calendar', }">Calendar</router-link>
        <router-link :to="{ name:'markdown', }">MarkDown</router-link>
    </div>
</template>
<script>
        import routes from '@/Router.js'
        export default{
            name: "NavbarTemplate",
            mounted(){
                console.log(routes);
            }
        }
</script>

//import {routes} from '@/Router.js'
// This returns a large object

谢谢。

【问题讨论】:

  • 为什么要导入路由?你在用 vue-router 吗?
  • 是的,我想遍历这条路线并创建一个动态导航栏。
  • 你试过export const routes吗?
  • 导出时使用router 而不是routes
  • 是的,我也在路由之前添加了导出,@Boussadjra_Brahim 的回答在一定程度上解决了我的问题。

标签: vue.js vue-router vuejs3 vue-router4


【解决方案1】:

你可以使用export const routeslike

export const routes = [
{
    path:"/",
    name:"home",
    component: HomeTemplate
},
...
]

然后像这样导入它:

 import { routes } from '@/Router.js'

或者您可以使用this.$router.getRoutes() 方法访问该路由:

<script>
    
        export default{
            name: "NavbarTemplate",
            mounted(){
                console.log(this.$router.getRoutes());
            }
        }
</script>

【讨论】:

  • 谢谢。你能解释一下为什么添加 {} 会给我这个数组吗?
  • 不客气,这是一种 ES6 语法,允许您从一个文件中导出多个模块,只有一个模块/变量可以默认导出并在不使用 {} 的情况下导入,但您导出多个模块仅使用export,您应该使用import {module1,module2,...} from '/someFile.js' 导入它们,例如您可以使用import router,{router} from @/Router``
  • @ChiragArora import stuff from './some-file' => 导入文件的默认导出并将其分配给当前范围内的stuffimport { stuff } from './some-file' 在文件的导出中查找任何名为 stuff 的导出,并将其分配给当前范围内的 stuff。这就是区别。
猜你喜欢
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 2018-11-02
  • 2020-03-27
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 2021-06-05
相关资源
最近更新 更多