// 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>

Logo

前往低代码交流专区

更多推荐