关于vue-router:P28-vue3-嵌套路由

36次阅读

共计 2167 个字符,预计需要花费 6 分钟才能阅读完成。

嵌套路由

App.vue

<script setup>


</script>

<template>
  <div>
    <h1>Hello App!</h1>

      <!-- 应用 router-link 组件进行导航 -->
      <!-- 通过传递 `to` 来指定链接 -->
      <!--`<router-link>` 将出现一个带有正确 `href` 属性的 `<a>` 标签 -->
      <router-link to="/">Go to Home</router-link>
      <p>---</p>
      <router-link to="/about">Go to About</router-link>
       <p>---</p>
      <router-link to="/user/56">Go to User</router-link>
    <p>---</p>
    <router-link to="/news/56">Go to User</router-link>
    <p>---</p>
    <router-link to="/parent">Go to Parent</router-link>

    <!-- 路由进口 -->
    <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view></router-view>


  </div>
</template>


index.js

// 1. 定义路由组件.
// 也能够从其余文件导入
import Home from "../views/Home.vue";
import About from "../views/About.vue";
import User from "../views/User.vue";
import NotFound from "../views/NotFound.vue";
import News from "../views/News.vue";
import Parent from "../views/Parent.vue";
import Styleone from "../views/Styleone.vue";
import Styletwo from "../views/Styletwo.vue";
import {createRouter, createWebHashHistory} from "vue-router";


// 2. 定义一些路由
// 每个路由都须要映射到一个组件。// 咱们前面再探讨嵌套路由。const routes = [{ path: '/', component: Home},
    {path: '/about', component: About},
    {path: '/user/:id', component: User},
    {//path: '/news/:id(\\d+)',// 正则匹配
        // path: '/news/:id+',// 多个参数
        //path: '/news/:id+',// 参数可有可无
        //path: '/news/:id*',// 参数可反复叠加
        path: '/news/:id?',// 参数不可反复叠加
        component: News
    },
    {path: '/:path(.*)',
        component: NotFound
    },// 应用正则,匹配任意 path
    {
        path: "/parent",
        component: Parent,
        children: [
            {
                path: "styleone",
                component: Styleone
            },
            {
                path: "styletwo",
                component: Styletwo
            }
        ]
    }
]

// 3. 创立路由实例并传递 `routes` 配置
// 你能够在这里输出更多的配置,但咱们在这里
// 临时放弃简略
const router = createRouter({
    // 4. 外部提供了 history 模式的实现。为了简略起见,咱们在这里应用 hash 模式。history: createWebHashHistory(),
    routes, // `routes: routes` 的缩写
})


export default router

Parent.vue

<template>
  <div>Parent </div>
  <router-link to="/parent/styleone"> 款式 1 </router-link>
  <router-link to="/parent/styletwo"> 款式 2 </router-link>
  <router-view></router-view>
</template>

<script>
export default {name: "Parent"}
</script>

<style scoped>

</style>

Styleone.vue

<template>
  <div>
    <p> 款式 1 </p>
    <ol>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>

    </ol>
  </div>
</template>

<script>
export default {name: "Styleone"}
</script>

<style scoped>

</style>

Styletwo.vue

<template>
  <div>
    <p> 款式 2 </p>
    <ol>
      <li>16</li>
      <li>26</li>
      <li>36</li>
      <li>46</li>

    </ol>
  </div>
</template>

<script>
export default {name: "Styletwo"}
</script>

<style scoped>

</style>

正文完
 0