Vue3 Vue-Router详解 Vue3配置hash 和 history路由、Vue3封装的路由hook函数(useRouter,useRoute)的使用 路由懒加载、路由分包处理、魔法注释的使用

// hash 模式
// import { createRouter, createWebHashHistory } from 'vue-router'

// history 模式
import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  // redirect 重定向 默认进入去到 home
  { path: '/', redirect: '/home' },
  {
    // name属性:路由记录独一无二的名称
    name: 'homeCom',
    // meta属性:自定义的数据
    meta: { name: 'HachimanC', age: 20 },
    // 跳转的路径
    path: '/home', 
    // 路由懒加载 路由分包处理  npm run build  /* webpackChunkName: "homeCom" */ => 魔法注释 分包后进行打包后 包的名字
    component: () => import(/* webpackChunkName: "homeCom" */ '../views/homeCom.vue')
  },
  // 传递 id
  { path: '/user/:id', component: () => import(/* webpackChunkName: "userCom" */ '../views/userCom.vue') },
  // 路径不正确显示
  { path: '/:pathMatch(.*)', component: () => import(/* webpackChunkName: "notFound" */ '../views/NotFound.vue') },
]

const router = createRouter({
  // history: createWebHashHistory(), // hash 模式
  history: createWebHistory(process.env.BASE_URL),  // history 模式
  routes,
})

export default router

 html部分

<template>
  <div>路由切换渲染</div>
  <router-link to="/home" active-class="linkClass">首页</router-link>
  <!-- replace 替换 点击不会返回上一页直接跳转浏览器首页 -->
  <router-link to="/user/123" replace>用户123</router-link>
  <router-link to="/user/321">用户321</router-link>
  <button class="btn" @click="jumpHandler('/home')">首页</button>
  <button class="btn" @click="jumpHandler('/user/123')">用户</button>
  <router-view></router-view>
</template>

js部分

<script setup>
import { useRouter } from 'vue-router'
const route = useRouter()
const jumpHandler = path => {
  // route.replace(path)
  route.push(path+`?name=Hachiman&age=20&id=123`)
}
</script>

<style scoped>
.linkClass {
  color: #ff0000;
  font-size: 20px;
}
.btn {
  border: none;
  background: #ff0000;
  margin: 0 10px;
}
</style>

 html页面使用路由传来的参数

<template>
  <h2>
    home组件 传递来的参数{{ $route.query }}
  </h2>
</template>

 获取router跳转id

<template>
  <h2>用户id: {{ $route.params.id }}</h2>
  <button @click="backHandler">返回</button>
</template>
<script setup>
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router'
const route = useRoute()
console.log(route.params.id)
// 获取 route 跳转 id
onBeforeRouteUpdate((to, from) => {
  console.log('from:', from.params.id)
  console.log('to:', to.params.id)
})
const router = useRouter()
const backHandler = () => {
  // 后退 和 前进
  // router.back()
  // router.forward()

  // go(1) => forward()
  // go(-1) => back()
  router.go(-1)
}
</script>

获取 路由跳转错误地址

<template>
    <div class="notFound">路径{{ $route.params.pathMatch }}不正确</div>
</template>
<style>
.notFound{
  font-size: 30px;
  color: red;
}
</style>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值