vue3 路由
vue3项目 vue cli
首先保证项目中引入了
package.json 文件内
其次路由文件 router.js 内
1 import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router"//123
2 import page404 from "../views/404.vue"
3 import Home from "../views/home.vue"
4 const routes: Array<RouteRecordRaw> = [ //32
5 {
6 path: "/",
7 name: "Home",
8 component: Home,
9 redirect: "/index",
10 children: [
11 {
12 path: "/index",
13 name: "Index",
14 meta: {
15 istoken: "首页"
16 },
17 component: () => import("@/views/index/index.vue")
18 },
19 {
20 path: "/about",
21 name: "About",
22 meta: {
23 istoken: "关于"
24 },
25 component: () => import("@/views/about/about.vue"),
26 redirect: "/about/groupIntroduction",
27 children: [
28 {
29 path: "/about/groupIntroduction",
30 name: "GroupIntroduction",
31 meta: {
32 text: "集团介绍"
33 },
34 component: () => import("@/views/about/groupIntroduction.vue")
35 },
36
37 ]
38 },
39
40
41 ]
42 },
43 { path: "/404", component: page404 },
44 { path: "/:catchAll(.*)", redirect: "/404" },
45 { path: '/news/newsDetail', name: 'NewsDetail',component: () => import("@/views/news/newsDetail.vue")},
46 { path: '/contact/juxianAccepted/recruitmentDetail', name: 'RecruitmentDetail', component: () => import("@/views/contact/juxianAccepted/recruitmentDetail.vue")}
47 ]
48
49 const router = createRouter({
50 history: createWebHashHistory(),
51 routes
52 })
53 router.afterEach((to,from,next) => {
54 window.scrollTo(0,0);
55 });
56 export default router
然后是获取所有路由名称路径的文件
1 <template>
2 <div class="home">
3 <page-top :home-title="routers" class="top"></page-top>
4 <div class="body">
5 <router-view></router-view>
6 </div>
7 <page-bottom :home-title="routers"></page-bottom>
8 </div>
9 </template>
10
11 <script lang="ts">
12 import { defineComponent, ref } from "vue";
13 import PageTop from "@/components/PageTop.vue";
14 import PageBottom from "@/components/PageBottom.vue";
15 import { useRoute, useRouter } from "vue-router"
16
17 export default defineComponent({
18 components: { PageTop, PageBottom },
19 setup() {
20 // 获取路由操作
21 const router = useRouter()
22 const route = useRoute()
23 const currentRoute = "/" + route.path.split("/")[1] //获取页面当前路径
24
25 // router.options.routes === 路由文件里面的路由数组
26 // router.options.routes.filter(i => i.path === "/")[0] === 通过filter里面的条件,过滤出一个新的数组,
27
28 // ==== 通过多次的filter过滤,返回新数组,拿到所需要的嵌套路由内的后代的数组
29 // router.options.routes.filter(i => i.path === "/")[0].children.filter(i => i.path === currentRoute)[0].children
30
31 const routers = router.options.routes.filter(i => i.path === "/")[0].children //此处是获取传到网站顶部和底部tabbar的数组
32 return { routers };
33 },
34 });
35 </script>
36
37 <style lang="scss" scoped>
38 .body {
39 min-height: 300px;
40 margin-top: 80px;
41 }
42 .top {
43 position: fixed;
44 top: 0;
45 left: 0;
46 z-index: 99;
47 width: 100%;
48 height: 80px;
49 background: #fff;
50 }
51 </style>
现在 return 出的 routers 已经是过滤好的路径数组,
传到需要使用的地方就可以使用了
忍一时,越想越气;
退一步,哎呦我去!