Vue3简易路由菜单组件封装

友情提醒:没有vue2的基础请先学习vue2,再来学习vue3,现在很多情况下还是使用vue2,这个组件倒是通用的,改点数据就好了,主要是思想。

组件Menu

<template>
  <div>
    <ul>
      <li v-for="menuItem in menuList" :key="menuItem.name">
        <router-link :to="menuItem.path">{{ menuItem.name }}</router-link>
        //判断子路由是否存在,这里的组件是自己调用自己,类似与递归,不要去想很多层了,递归我们算法老师教了,最多想到第二层,对于普通人来说,我就只想到第二层了,我是普通人哈哈哈哈。为什么用了一个v-if,提升一下性能,不能盲目创建,判断一下有没有再创建不会随意渲染dom,v-show的话只是隐藏了
        <MenuList
          v-if="menuItem.children"
          :menuList="menuItem.children"
        ></MenuList>
      </li>
    </ul>
  </div>
</template>

<script setup>
import MenuList from "./index.vue";
//menuList是获取到路由里面的数组传过来的值
let menuListProps = defineProps({
  menuList: {
    type: Array,
    default: [],
  },
});
console.log(1);
</script>

<style scoped>
ul li {
  list-style: none;
}
</style>

如何用这个组件

//任意父组件(App.vue)
<template>
	<div>
	 <div id="menuBox"><menuComponent :menuList="menuList" /></div>
	 //仔细看这里,如果你要用二级三级四级路由,这里你都不得不在父路由当中加入。
    <div><router-view></router-view></div>
	</div>
</template>
<script setup>
我这里是放在了App.vue文件里面
import menuComponent from "../src/views/menu/index.vue";
import router from "./router/index";
let menuList = ref(router.options.routes);
</script>

router.js文件

import { createRouter, createWebHistory } from "vue-router"
import Home from "../views/home/index.vue"
console.log(Home)
const routes = [
    {
        path: "/",
        name: "Home",
        component:Home
    },
    {
        path: "/about",
        name: "About",
        component:()=>import('../views/about/index.vue')
    },
    {
        path: '/total',
        name: 'total',
        component: () => import("../views/transmit/total.vue"),
        children: [
            { path: '/total/about', name: "total子路由1", component: () => import("../views/about/index.vue") },
             {path:'/total/home',name:"total子路由2",component:()=>import("../views/home/index.vue")}
        ]
    },
    {
        path: '/slot',
        name: 'slot',
        component:()=>import("../views/slot/index.vue")
    }, {
        path: '/teleport',
        name: 'teleport',
        component: () => import("../views/teleport/index.vue"),
        
    }, {
        path: '/mixin',
        name: 'mixin',
        component:()=>import("../views/mixin/index.vue")
        
    }
]
const router = createRouter({
    history: createWebHistory(),
    routes
})
router.beforeEach((to,from,next) => { 
    next();
})
export default router

你可能感兴趣的:(vue.js,前端,javascript)