68.vue2.0学习 —— vue-router

相关理解

vue-router的理解

vue的一个插件库,专门用来实现SPA应用

对SPA应用的理解

  1. 单页Web应用(single page web application,SPA)。
  2. 整个应用只有一个完整的页面。
  3. 点击页面中的导航链接不会刷新页面,只会做页面的局部更新。
  4. 数据需要通过ajax请求获取。

路由的理解

  1. 什么是路由?
    1. 一个路由就是一组映射关系(key - value)
    2. key为路径, value可能是function或component
  2. 路由分类
    1. 后端路由:
      1. 理解:value是function, 用于处理客户端提交的请求。
      2. 工作过程:服务器接收到一个请求时, 根据请求路径找到匹配的函数来处理请求, 返回响应数据。
    2. 前端路由:
      1. 理解:value是component,用于展示页面内容。
      2. 工作过程:当浏览器的路径改变时, 对应的组件就会显示。

路由的基本使用

  1. 下载vue-router插件

    npm install vue-router
    
  2. 定义路由表

    // routers.js
    
    import vueRouter from 'vue-router'
    import Home from '../components/home'
    import About from '../components/about'
    export default new vueRouter({
      mode: 'history', //路由模式, 默认值是hash
      routes: [
        {
          path: '/home',
          component: Home,
        },
        {
          path: '/about',
          component: About,
        },
      ],
    })
    
    
  3. 在项目中配置路由表和路由插件

    //引入Vue
    import Vue from 'vue'
    //引入App
    import App from './App.vue'
    //引入vueRouter插件
    import vueRouter from 'vue-router'
    // 引入路由表
    import router from './routers'
    //关闭Vue的生产提示
    Vue.config.productionTip = false
    //使用插件
    Vue.use(vueRouter)
    //创建vm
    new Vue({
      el: '#app',
      render: (h) => h(App),
      // 配置路由表
      router,
    })
    
  4. 在组件中使用router-view和router-link

    <template>
      <div>
        <!-- router-link 可以改变浏览器地址栏地址,但不发送请求 -->
        <!-- active-class 定义高亮类名 -->
        <router-link to="/home" active-class="selected">home</router-link>
        <!-- router-link 上添加replace就不记录历史 -->
        <router-link replace to="/about">about</router-link>
        <!-- router-view 用于展示路由组件 --> 
        <router-view></router-view>
      </div>
    </template>
    

多级路由(嵌套路由)

import vueRouter from 'vue-router'
import Home from '../components/home'
import About from '../components/about'
import News from '../components/news'
import Message from '../components/message'
export default new vueRouter({
  routes: [
    {
      path: '/',
      component: Home,
    },
    {
      path: '/home',
      component: Home,
      children: [
        {
          path: 'news',
          component: News,
        },
        {
          path: 'message',
          component: Message,
        },
      ],
    },
    {
      path: '/about',
      component: About,
    },
  ],
})

在Home组件中配置router-link和router-view
<template>
  <div>
    <h1>这是home组件</h1>
    <router-link to="/home/news">news</router-link>
    <router-link to="/home/message">message</router-link>
    <router-view></router-view>
  </div>
</template>

命名路由

routers.js

{
    name:'xiangqing',  // 给detail组件命名
    path:'detail',
    component:Detail,
}
    
    
跳转时,指定路由名称
<router-link :to="{name:'xiangqing'}">detail</router-link>

路由传参

query参数(查询字符串)

news.vue 
<template>
  <div>
    <h2>news组件</h2>
    <!-- 传递参数 -->
    <router-link to="/home/news/detail?name=zs&age=18">detail</router-link>
    <!-- 另外一种写法: -->
    <router-link :to="{
					path:'/home/news/detail',
					query:{
						name: 'zs',
                      	age: 18
					}
				}">
	</router-link>
    <!-- 展示detail组件的位置 -->
    <router-view></router-view>
  </div>
</template>

detail.vue
<template>
  <div>
    <h3>detail组件</h3>
    <!-- 接收数据 -->
    <div>query: {{ $route.query.name }}</div>
    <div>query: {{ $route.query.age }}</div>
  </div>
</template>

params参数(路由参数)

路由表中配置路由参数
{
    name: 'xiangqing',
    path: 'detail/:name?/:age?',
    component: detail,
},

news.vue 
<template>
  <div>
    <h2>news组件</h2>
    <!-- 传递参数 -->
    <router-link to="/home/news/detail/zs/18">detail</router-link>
    <!-- 另外一种写法: -->
    <router-link :to="{
					path:'/home/news/detail/:name/:age',
					params:{
						name: 'zs',
                      	age: 18
					}
				}">
	</router-link>
    <!-- 展示detail组件的位置 -->
    <router-view></router-view>
  </div>
</template>

detail.vue
<template>
  <div>
    <h3>detail组件</h3>
    <!-- 接收数据 -->
    <div>query: {{ $route.params.name }}</div>
    <div>query: {{ $route.params.age }}</div>
  </div>
</template>

props参数

{
     name: 'xiangqing',
     path: 'detail/:name/:age',
     component: detail,
     //props的第一种写法,值为对象,该对象中的所有key-value都会以props的形式传给Detail组件。
     // props: { num1: 1, num2: 2 },

     //props的第二种写法,值为布尔值,若布尔值为真,就会把该路由组件收到的所有params参数,以props的形式传给Detail组件。
     // props: true,
         
     //props的第三种写法,值为函数
     props($route) {
         return {
             name: $route.params.name,
             age: $route.params.age,
             a: 1,
             b: 'hello',
         }
     },
},

编程式导航

 methods: {
    pushHandle() {
      this.$router.push({
        // path: '/home/news/detail/ls/20',
        name: 'xiangqing',
        params: {
          name: 'ls',
          age: 20,
        },
      })
    },
    replaceHandle() {
      this.$router.replace({
        path: '/home/news/detail/wu/30',
      })
    },
 },
     
 // 其他方法: 
  $router.go
  $router.back()
  $router.forward()

缓存路由组件

<!-- 缓存一个路由组件  news是组件名  组件名需要在组件的配置对象中配置: name: '组件名'-->
<keep-alive include="news">
    <router-view></router-view>
</keep-alive>

<!-- 缓存多个路由组件 -->
<keep-alive :include="['news','message']">
    <router-view></router-view>
</keep-alive>

<!-- 不写include, 会缓存所有会出现在router-view位置的组件 -->
<keep-alive >
    <router-view></router-view>
</keep-alive>

两个新的周期周期钩子

// 注意:配合缓存组件使用
activated() {
    console.log('News组件被激活了')
},
deactivated() {
    console.log('News组件失活了')
},

路由守卫

全局路由守卫

const router = new vueRouter({
  routes: [
    {
      path: '/home',
      component: Home,
      meta: { isAuth: true, title: '首页' },
      children: [
        {
          path: 'news',
          component: news,
          meta: { isAuth: true, title: '新闻' },
          children: [
            {
              name: 'xiangqing',
              meta: { isAuth: true, title: '详情' },
              path: 'detail/:name/:age',
              component: detail,
            },
          ],
        },
        {
          path: 'message',
          component: message,
        },
      ],
    },
    {
      path: '/about',
      component: About,
    },
  ],
})

// 前置路由守卫 -- 初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
  // to: 目标路由信息
  // from: 起始路由信息
  // next: 是一个函数,如果调用则跳转到指定路径,否则不跳转
  console.log('前置路由守卫执行了', to, from)
  // meta是在路由表中配置的元信息.
  if (to.meta.isAuth) {
    //一般登录之后,会在本地缓存中存储一个token.如果登录了就可以跳转到指定路由,没有登录就不跳转
    localStorage.getItem('token') ? next() : undefined
    return
  }
  next()
})

//全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to, from) => {
  console.log('后置路由守卫', to, from)
  document.title = to.meta.title || '硅谷系统'
})
export default router

独享路由守卫

{
   name: 'xiangqing',
   meta: { isAuth: true, title: '详情' },
   path: 'detail/:name/:age',
   component: detail,
   // 在进入指定路由之前
   beforeEnter: function(to, from, next) {
       console.log('独享路由守卫执行了', to, from)
       if (to.meta.isAuth) {
           localStorage.getItem('token') ? next() : undefined
           return
       }
       next()
   },
}

组件内路由守卫

// 组件的配置对象中

export default {
 
  //通过路由规则,进入该组件时被调用
  beforeRouteEnter(to, from, next) {
    console.log('组件内路由守卫-进入之前', to, from)
    if (to.meta.isAuth) {
      if (to.meta.isAuth) {
        localStorage.getItem('token') ? next() : undefined
        return
      }
      next()
    }
  },

  //通过路由规则,离开该组件时被调用
  beforeRouteLeave(to, from, next) {
    console.log('组件内路由守卫-离开时', to, from)
    next()
  },
}

🌺相关推荐:上一篇:vuex       下一篇:上线部署(nginx)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值