06Vue3-Vue路由笔记

路由基本用法

文件目录结构
06Vue3-Vue路由笔记_第1张图片

route->index.js配置文件解读

import {
      createRouter, createWebHistory } from 'vue-router'
//引入组件
import Home from '../views/Home.vue'
import User from '../views/User.vue'
//等价于
//const Home = () => import('../views/Home.vue')
//const About = () => import('../views/About.vue')

//声明一个路由规则,访问home,加载Home组件
const routes = [
  {
     
    path: '/',
    name: 'Home',
    component: Home
  },
  {
     
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
     
	path: '/user',
	component: User	
  }
]

// 创建一个路由
const router = createRouter({
     
  //模式为历史模式,请求过的路由会push,类似于window.history.pushState() 
  history: createWebHistory(process.env.BASE_URL),
  //路由规则
  routes
})
//缺省暴露路由
export default router

路由的三种模式
在这里插入图片描述
路由两种自带标签
在这里插入图片描述

路由有两种全局属性
$route : 当前正在访问的路由
$router:代表整个大的路由器的对象

App.vue 触发路由的几种操作

<template>
  <div id="nav">

    <router-link to="/">Homerouter-link> |
    <router-link to="/about" >关于router-link> |
    <router-link to="/about" custom v-slot="{ navigate }">
      <button @click="navigate" @keypress.enter="navigate" role="link">关于button>
    router-link> |
    <button :class="{active:$route.path='/user'}" @click="$router.push('/user')">个人中心button>|
    <button @click="$router.go(-1)">返回button>|
    {
    {$route.path}}
  div>
  <hr>
  <router-view/>
template>

06Vue3-Vue路由笔记_第2张图片
06Vue3-Vue路由笔记_第3张图片
若要一个页面显示三个不同的组件
App.vue

<template>
  <div id="nav">

    <router-link to="/">Homerouter-link> |
    <router-link to="/about" >关于router-link> |
    <router-link to="/about" custom v-slot="{ navigate }">
      <button @click="navigate" @keypress.enter="navigate" role="link">关于button>
    router-link> |
    <button :class="{active:$route.path=='/user'}" @click="$router.push('/user')">个人中心button>|
    <button @click="$router.go(-1)">返回button>|
    {
    {$route.path}}
  div>
  <hr>

  <router-view class="one" name="User">router-view>
  <router-view class="two" >router-view>
  <router-view class="three" name="About">router-view>
template>

<style>
#app {
      
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
      
  padding: 30px;
}

#nav a {
      
  font-weight: bold;
  color: #2c3e50;
}

#nav a.router-link-exact-active {
      
  color: #42b983;
}
.active {
      
  color: red !important
}
.one {
      
  width: 25%;
  height: 300px;
  float: left;
  background-color: #42b983;
}
.two {
      
  width: 50%;
  height: 300px;
  float: left;
  background-color: cornflowerblue;
}
.three {
      
  width: 25%;
  height: 300px;
  float: left;
  background-color: coral;
}
style>

index.js

import {
      createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import User from '../views/User.vue'
import About from '../views/About.vue'
const routes = [
  {
     
    path: '/',
    name: 'Home',
    //对象格式,排序也有关系的
    components: {
     
      default: Home,
      About,
      User
    }
    // component: Home
  },
  {
     
    path: '/user',
    name: 'user',
    component: User
  },
  {
     
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = createRouter({
     
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

06Vue3-Vue路由笔记_第4张图片
06Vue3-Vue路由笔记_第5张图片

嵌套路由

User.vue

<template>
  <div class="about">
    <h1>This is an User pageh1>
    <br>
    <div class="menu">
      <ul>
        <li><router-link to="/user/order">我的订单router-link>li>
        <li><router-link to="/user/setting">个人设置router-link>li>
      ul>

    div>
    <div class="content">
      <router-view>router-view>
    div>

  div>
template>
<script>
export default {
      
  name: "User"
}
script>

<style scoped>
.menu {
      
  width: 30%;
  height: 300px;
  background-color: #42b983;
  float: left;
}
.content {
      
  width: 70%;
  height: 300px;
  background-color: floralwhite;
  float: right;
}
style>

index.js路由设置

import {
      createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import User from '../views/User.vue'
import About from '../views/About.vue'
import Order from '../views/UserOrder.vue'
import Setting from '../views/UserSetting.vue'

//等价于
//const Home = () => import('../views/Home.vue')
//const About = () => import('../views/About.vue')
import * as path from "path";
const routes = [
  {
     
    path: '/',
    name: 'Home',
    component: Home
  },
  {
     
    path: '/user',
    name: 'user',
    component: User,
    //子路由,/user/order
    children: [
        //设置默认组件
      {
     
        path: '',
        component: Order
      },
      {
     
        path: 'order',
        component: Order
      },
      {
     
        path: 'setting',
        component: Setting
      }
    ]
  },
  {
     
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = createRouter({
     
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

06Vue3-Vue路由笔记_第6张图片

06Vue3-Vue路由笔记_第7张图片

路由传递参数方式

06Vue3-Vue路由笔记_第8张图片
上个嵌套路由的例子,“我的订单”和“个人设置”是采用切换组件来实现,下边采用传递参数来实现页面的切换,即同个模板,传递参数值来切换

params 方式

User.vue

<template>
  <div >
    <h1>This is an User pageh1>
    <br>
    <div class="menu">
        ……
      <ul>
        <li v-for="item in article">
         
          <router-link :class="{active:$route.params.pid==item.id}" :to="'/user/page/'+item.id">{
    {item.title}}router-link>
        li>
      ul>
    div>
    <div class="content">
      <router-view>router-view>
    div>

  div>
template>
<script>
export default {
      
  name: "User",
  data(){
      
    return {
      
      article: [
        {
      id:10, title: '这是文章一'},
        {
      id:11, title: '这是文章二'},
        {
      id:12, title: '这是文章三'},
        {
      id:13, title: '这是文章四'},
        {
      id:14, title: '这是文章五'},
      ]
    }
  }
}
script>

<style scoped>
……
style>

添加一个UserPage.vue

<template>

  <h2>这是文章的模板h2>

  文章ID:{
    {$route.params.pid}}
  <br>
  <h1>{
    {pageid}}h1>
template>

<script>
export default {
      
  name: "UserPage",
  computed: {
      
    pageid() {
      
    //获取当前路由属性的参数值pid
      return this.$route.params.pid;
    }

  }
}
script>

<style scoped>style>

index.js路由配置

const routes = [
  ……
  {
     
    path: '/user',
    name: 'user',
    component: User,
    //子路由,/user/order
    children: [
        //设置默认组件
     ……
      {
     
       //动态路由配置
        path: 'page/:pid',
        component: Page
      }
    ]
  },
  ……
]

06Vue3-Vue路由笔记_第9张图片

Query的方式

User.vue

<template>
  <div>
    <h1>This is an User page</h1>
    <br>
    <div class="menu">
     ……
      <ul>
        ……
        <br>
			<!-- 三种格式-->
        <li><router-link to="/user/article?name=zs&age=10">文章一</router-link></li>
        <li><router-link :to="{path:'/user/article', query:{name:'lisi', age:20}}">文章二</router-link></li>
        <br>
        <li><button @click="$router.push({path:'/user/article', query: {name:'word', age:99}})">文章三</button></li>
      </ul>
    </div>
    <div class="content">
      <router-view></router-view>
    </div>

  </div>
</template>
<script>
export default {
     
  name: "User",
  data(){
     
    return {
     
      article: [
        ……
      ]
    }
  }
}
</script>

<style scoped>
……
</style>

添加一个Article.vue

<template>
  这是文章内容
  <br>
  name:{
    {$route.query.name}}<br>
  age:{
    {$route.query.age}}<br>
template>

<script>
export default {
      
  name: "Article"
}
script>

<style scoped>

style>

index.js路由配置

const routes = [
  ……
  {
     
    path: '/user',
    name: 'user',
    component: User,
    //子路由,/user/order
    children: [
        //设置默认组件
     ……
      {
     
        path: 'article',
        component: Article
      }
    ]
  },
  ……
]

06Vue3-Vue路由笔记_第10张图片

重定向和别名

06Vue3-Vue路由笔记_第11张图片

导航守卫

路由的导航守卫主要用来通过跳转或取消的方式守卫导航
前置守卫:从一个路由跳转另一个路由之前有一个前置守卫,前置守卫会调用一个方法,这个方法可以处理跳转之前的事情。如登录访问
在这里插入图片描述

后置钩子:跳转过去之后,在内容没显示之前,有一个后置钩子
在这里插入图片描述
06Vue3-Vue路由笔记_第12张图片
index.js

const routes = [
  {
     
    path: '/home',
    name: 'Home',
    //重定向到根 两种方式
    // redirect: '/',
    redirect: {
     name: 'root'},
    component: Home,
    meta: {
     
      title: '首页'
    },
  },
  ]
  ……
//全局导航守卫
router.beforeEach((to,from)=>{
     
  console.log('前置守卫');
  //设置即将到达的页面标题,meta是上方各个路由设置的meta属性
  document.title = to.meta.title
  console.log('title---'+to.meta.title);
  //打印即将到达的路径
  console.log('to---'+to.fullPath);
  //false不准跳转,true则放行
  return true;
})

//后置钩子
router.afterEach((to,form)=>{
     
  console.log('后置钩子');
  console.log('to---'+to.fullPath);
  console.log('form---'+form.fullPath);
})

06Vue3-Vue路由笔记_第13张图片

keep-alive和vue-router结合

06Vue3-Vue路由笔记_第14张图片
组件切换时,会已处在创建-销毁的过程中,为节省时间和资源,采用keep-alive使其保存在缓存中

	created() {
     
      console.log('About---组件创建');
    },
    unmounted() {
     
      console.log('About---组件被销毁');
    },
    activated() {
     
      console.log('About---keep-alive 缓存的组件激活时调用');
    },
    deactivated() {
     
      console.log('About---keep-alive 缓存的组件停用时调用');
    }

06Vue3-Vue路由笔记_第15张图片

只要将router-view修改如下代码,就可实现缓存效果

<router-view v-slot="{ Component }">
    <transition>
      <keep-alive>
        <component :is="Component" />
      </keep-alive>
    </transition>
  </router-view>

这种方法会触发actived()和deactivated()方法
06Vue3-Vue路由笔记_第16张图片
可单独设置某些组件不缓存

<router-view v-slot="{ Component }">
    <transition>
      <keep-alive exclude="About">
        <component :is="Component" />
      </keep-alive>
    </transition>
  </router-view>

06Vue3-Vue路由笔记_第17张图片
为了保证离开一个页面后再返回仍停留在离开时的状态,可在组件内设置前置守卫,将离开时的路径保存下来,待缓存激活active时再设置全局路由

 created() {
     
    console.log('User---组件创建');
  },
  unmounted() {
     
    console.log('User---组件被销毁');
  },
  activated() {
     
    console.log('User---keep-alive 缓存的组件激活时调用');
    //回到离开时的状态
    this.$router.push(this.path)
  },
  deactivated() {
     
    console.log('User---keep-alive 缓存的组件停用时调用');
  },
  beforeRouteLeave(to,from) {
     
    //获取离开的路由
    this.path = from.fullPath
    console.log('to----'+to.fullPath);
    console.log('from----'+from.fullPath);
  }

你可能感兴趣的:(Vue3,学习,vue)