vue-router笔记

本文介绍了如何使用vue-router构建SPA,包括安装、配置路由、组件组织、路由传参、命名路由、路由生命周期钩子和路由守卫的使用,以及history模式下的部署策略和element-ui的按需引入。
摘要由CSDN通过智能技术生成

目的:为了实现SPA(单页面应用)

vue-router是一个插件库

安装:

npm i vue-router@3

路由的配置路径:/src/router/index.js

路由组件的目录:/src/pages/

一般组件的目录:/src/components/

// 该文件专门用于创建整个应用的路由器
import Vue from 'vue'
import VueRouter from 'vue-router'
//引入组件
import About from '../components/About'
import Home from '../components/Home'

Vue.use(VueRouter)
//创建并暴露一个路由器
export default new VueRouter({
    routes: [
        {
            path: '/about',
            component: About
        },
        {
            path: '/home',
            component: Home
        }
    ]
})

使用:

main.js:

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap'
//引入路由器 我们编写的配置类
import router from './router'
//关闭Vue的生产提示
Vue.config.productionTip = false
//创建vm
new Vue({
    el: '#app',
    render: h => h(App),
    router: router
})

App.vue:

<template>
  <div>
    <div class="row">
      <div class="col-xs-offset-2 col-xs-8">
        <div class="page-header"><h2>Vue Router Demo</h2></div>
      </div>
    </div>
    <div class="row">
      <div class="col-xs-2 col-xs-offset-2 col-2">
        <div class="list-group">
          <!-- Vue中借助router-link标签实现路由的切换 -->
          <router-link active-class="active" class="list-group-item" to="/about">About</router-link>
          <router-link active-class="active" class="list-group-item" to="/home">Home</router-link>
        </div>
      </div>
      <div class="col-xs-6 col-6">
        <div class="panel">
          <div class="panel-body">
            <!-- 指定组件的呈现位置 -->
            <router-view></router-view>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
}
</script>

About.vue:

<template>
  <h2>我是About的内容</h2>
</template>

<script>
export default {
  name: 'About'
}
</script>

不可见的路由组件在哪?        被销毁了

嵌套路由的案例:

<div>
  <h2>我是Home的内容</h2>
  <div class="nav nav-tabs">
    <router-link active-class="active" class="list-group-item" to="/home/news">news</router-link>
    <router-link active-class="active" class="list-group-item" to="/home/message">message</router-link>
  </div>
  <div>
    <router-view></router-view>
  </div>
</div>
{
    path: '/home',
    component: Home,
    children: [
        // 此处不加/了
        {path: 'news', component: News},
        {path: 'message', component: Message},
    ]
}

路由传参:

query:

传参:

<router-link :to="`/home/message/detail?id=${i.id}&title=${i.title}`">{{ i.title }}</router-link>

接收:

<li>消息编号:{{ $route.query.id }}</li>
<li>消息标题:{{ $route.query.title }}</li>

对象写法:

<router-link :to="{
    path:'/home/message/detail',
    query:{
      id:i.id,
      title:i.title,
    }
}">
  {{ i.title }}
</router-link>

命名路由,个人认为没有路径方便:

子路由配置:

{
    name: 'xiangqing',
    path: 'detail',
    component: Detail
}

父路由调用者:

<router-link :to="{
      name:'xiangqing',
      query:{
        id:i.id,
        title:i.title,
      }
 }">
  {{ i.title }}
</router-link>

params传参方式,params的第一种方式:

类似于RestFul风格

子类接收方:

<li>消息编号:{{ $route.params.id }}</li>

父类发送方:

<router-link :to="`/home/message/detail/${i.id}/${i.title}`">
  {{ i.title }}
</router-link>

params传参props接收,params的第二种方式:

children: [
    {
        path: 'detail/:id/:title',
        component: Detail,
        /* 把子路由组件收到的params参数以
         *  prop的形式接收
         */
        props: true,
    }
]
// 比上一种更加简洁
<li>消息编号:{{ id }}</li>

props: ['id']
<router-link :to="`/home/message/detail/${i.id}/${i.title}`">
  {{ i.title }}
</router-link>

query传递prop接收的方式:

{
    path: 'detail',
    component: Detail,
    props({query:{id,title}}) {
        return {id,title}
    }
}
<router-link :to="`/home/message/detail?id=${i.id}&title=${i.title}`">
  {{ i.title }}
</router-link>

replace属性:关闭浏览器左上角的后退和前进的记录,改为replace模式

不用<router-link>标签的情况下,实现路由跳转

自动延迟跳转,编程式路由导航:

this.$router.forward()
this.$router.back()
this.$router.go(1)

如何让组件隐藏后不销毁,这样子路由的News组件切走就不会被销毁了,如果不写News,全部子路由组件都不会销毁

<keep-alive include="News">
  <router-view></router-view>
</keep-alive>

但是组件不销毁,定时器会一直运行

路由的生命周期钩子:

activated() {
  // 组件激活后触发 路由组件专属
  console.log('组件激活后触发')
  this.timer = setInterval(() => {
    this.opacity -= 0.01
    if (this.opacity < 0) this.opacity = 1
  }, 16)
},
deactivated() {
  // 组件失活后触发 路由组件专属
  console.log('组件失活后触发')
  clearInterval(this.timer)
},

路由守卫:

访问路径前先验证身份

全局前置路由守卫:

写在路由配置类里:

// 全局前置路由守卫,初始化也会被调用
router.beforeEach((to, from, next) => {
    if (to.path === '/home/message') {
        if (localStorage.getItem('school') === 'ABC') next()
        else alert('学校名不对 权限不足')
    } else {
        next()
    }
})
export default router

第二种判断是否要鉴权的方式:

{name: 'xinwen', path: 'news', component: News, meta: {isAuth: true}}

router.beforeEach((to, from, next) => {
    if (to.meta.isAuth === true) {
        if (localStorage.getItem('school') === 'ABC') next()
        else alert('学校名不对 权限不足')
    } else {
        next()
    }
})

全局后置路由守卫:

router.afterEach(from => {
    /*
     * 切换完了才调用,切换无权限不会调用
     * 需求:改变网站的title之类的业务
     */
    if (from.meta.title === undefined) return
    document.title = from.meta.title
})

独享路由守卫:

{
    name: 'xinwen',
    path: 'news',
    component: News,
    meta: {isAuth: true, title: '新闻'},
    beforeEnter: ((to, from, next) => {
        // 限制业务代码
        if (localStorage.getItem('school') === 'ABC') {
            next()
        } else {
            alert('学校名不对 权限不足')
        }
    })
},

组件内的路由守卫:

写在组件内

beforeRouteEnter(to, from, next) {
  /*
   * 通过路由规则,进入该组件前被调用
   * 初始化加载导致进入后,不会被调用
   */
  next()
},
beforeRouteLeave(to, from, next) {
  // 通过路由规则,离开该组件前被调用
  // 放行
  next()
}
const router = new VueRouter({
    mode:history,
})

/#/        hash

history模式        与hash模式相比,没有/#/号,非常旧的浏览器可能不支持

/#/home/message        hash值,/#/开头的内容不会发给服务器,如果用户刷新,会发起请求后端

解决方案:

服务器:

npm i connect-history-api-fallback

加上:

const history = require('connect-history-api-fallback')
app.use(history())

项目写完后构建项目:

npm run build

项目名/dist/        打包后的文件

前端项目部署上线:

npm init

输入项目名

选项默认

npm i express

新建server.js,编写服务器启动业务代码:

const express = require('express')
const app = express()
app.use(express.static(__dirname + '/static'))
app.listen(80, err => {
    if (!err) console.log('服务器启动成功了')
})

新建static或者叫public目录

将之前dist目录下的构建好的html等项目文件,放到刚刚新建的static目录下

服务器启动:node server

element-ui按需引入:

生产的时候

官网的教程按需引入的地址:

组件 | Element

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蒋劲豪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值