Vue3 Router

1.index.js

点击查看代码
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {path: '/',redirect: '/home'},
    {path: '/manager',component: () => import('../views/Manager.vue'),children: [
        // 子路由去斜杠
        {path: 'home', name: 'home', meta: {title: '首页'},component: () => import('../views/Home.vue'),},
        {path: 'test', name: 'test', meta: {title: '测试'},component: () => import('../views/test.vue'),},

      ]},
      {path: '/404', name: 'NotFound', meta: {title: '404找不到页面'},component: () => import('../views/404.vue'),},
  ],
})
// 跳转前的操作
router.beforeEach((to, from, next) => {
  document.title = to.meta.title
  next()//必须调用
})
export default router

2.前端使用
点击查看代码
<div style="margin-bottom: 20px">
    <RouterLink to="/test">通过router跳转到test</RouterLink>
    <br>

    <a href="/test">通过a跳转到test</a>
  </div>

  <div style="margin-bottom: 20px">
    <el-button type="primary" @click="router.push('test')">push跳转到新的页面</el-button>
<!--    无返回-->
    <el-button type="primary" @click="router.replace('test')">replace跳转到新的页面</el-button>
  </div>

  <div style="margin-bottom: 20px">
<!--    参数都为query类型-->
    <el-button type="primary" @click="router.push('test?id=1&name=wddw')">路由传参id=1&name=wddw</el-button>
  </div>

  <div style="margin-bottom: 20px">
    <el-button type="primary" @click="router.push({path:'test',query:{id:2,name:'wddw'}})">路由传参id=2&name=wddw</el-button>
  </div>
3.404页面制作
点击查看代码


<template>
  <div style="text-align: center">
    <img src="@/assets/very_sorry.png" alt="">
    <div>
      <el-button type="primary" style="width: 150px;height: 60px;font-size: 20px" @click="goHome">返回首页</el-button>
    </div>
  </div>

</template>

<style scoped>

</style>
<script setup>
import {createRouter as $router} from "vue-router";
const goHome = () =>{
  location.href="/manager/home"
}
</script>
posted @ 2025-03-17 21:23  QixunQiu  阅读(9)  评论(0)    收藏  举报