如何使用 Vue Router 的 router-view 组件

发布于 2022-12-14 13:25:14 字数 1642 浏览 96 评论 0

路由器的视图 <router-view>component 显示与当前 URL 对应的组件或模板。

<script src="https://unpkg.com/vue@3"></script>
<script src="https://unpkg.com/vue-router@4"></script>

<div>
  <div>
    <router-link to="/home">Go to Home</router-link> <br />
    <router-link to="/about">Go to About</router-link>
  </div>
  <h1>Observe the Change Below!</h1>
  <router-view></router-view>
</div>
<script>
  const routes = [
    { path: '/home', component: { template: '<div>Home</div>' } },
    { path: '/about', component: { template: '<div>About</div>' } }
  ];
  const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes,
  });
  const app = Vue.createApp({});
  app.use(router);
  app.mount('#app');
</script>

观察下面的变化

Props

注意 router-view 只需要一个 Props, name 你不能使用 router-view 要将 Props 传递给渲染的组件,您需要使用 props 路线选项

const router = VueRouter.createRouter({
  {
    path: '/user/:id',
    component: app.component('user'),
    // Pass the `id` route parameter as the `userId` prop.
    props: (route) => {
      return {
        userId: route.params.id
      };
    }
  }
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

文章
评论
25 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文