VueRouter--路由
这里的路由是SPA(单页应用)的路径管理器。再通俗的说,vue-router就是WebApp的链接路径管理系统。
vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,适合用于构建单页面应用。vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起来。传统的页面应用,是用一些超链接来实现页面切换和跳转的。在vue-router单页面应用中,则是路径之间的切换,也就是组件的切换。路由模块的本质 就是建立起url和页面之间的映射关系。
至于为什么不能用a标签?这是因为用Vue做的都是单页应用(当你的项目准备打包时,运行npm run build时,就会生成dist文件夹,这里面只有静态资源和一个index.html页面),所以你写的<a></a>标签是不起作用的,你必须使用vue-router来进行管理。
一、vue-router实现原理:
SPA(single page application):单一页面应用程序,只有一个完整的页面;它在加载页面时,不会加载整个页面,而是只更新某个指定的容器中内容。单页面应用(SPA)的核心之一是: 更新视图而不重新请求页面;vue-router在实现单页面前端路由时,提供了两种方式:Hash模式和History模式;根据mode参数(mode:'hash')来决定采用哪一种方式。
1、Hash模式:
vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。 hash(#)是URL 的锚点,代表的是网页中的一个位置,单单改变#后的部分,浏览器只会滚动到相应位置,不会重新加载网页,也就是说hash 出现在 URL 中,但不会被包含在 http 请求中,对后端完全没有影响,因此改变 hash 不会重新加载页面;同时每一次改变#后的部分,都会在浏览器的访问历史中增加一个记录,使用”后退”按钮,就可以回到上一个位置;所以说Hash模式通过锚点值的改变,根据不同的值,渲染指定DOM位置的不同数据。hash 模式的原理是 onhashchange 事件(监测hash值变化),可以在 window 对象上监听这个事件。
1、Histoey模式:
由于hash模式会在url中自带#,如果不想要很丑的 hash,我们可以用路由的 history 模式,只需要在配置路由规则时,加入"mode: 'history'",这种模式充分利用了html5 history interface 中新增的 pushState() 和 replaceState() 方法。这两个方法应用于浏览器记录栈,在当前已有的 back、forward、go 基础之上,它们提供了对历史记录修改的功能。只是当它们执行修改时,虽然改变了当前的 URL ,但浏览器不会立即向后端发送请求。
当你使用 history 模式时,URL 就像正常的 url,例如 http://yoursite.com/user/id,比较好看!
不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 http://oursite.com/user/id 就会返回 404,这就不好看了。
所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。
{path: "*", redirect: "/"}]
//此处就设置如果URL输入错误或者是URL 匹配不到任何静态资源,就自动跳到到Home页面
二、vue-router使用
1、安装路由
npm istall vue-router --save
2、在src/router/inde.js文件中引入、使用路由
import VueRouter from 'vue-router' //引入路由
Vue.use(VueRouter) 使用路由
3、在src/main.js文件中引入路由配置文件index.js文件,并将路由对象传递给vue实例
import router from './router' //引入路由配置文件
Vue.use(VueRouter) 使用路由
new Vue({
el: '#app',
router, //传递路由对象给vue实例
render: h => h(App)
})
4、在src/router/inde.js配置路由
import Index from './路径/Index' //引入组件
const router = new VueRouter({
mode:'history', //history模式,可以去除URL里面的hash符号(#)
routes:[ //注册组件路由,
{
path:'/', //path设置路径,'/'表示根路径
conponent:Index, //设置的路径对应的组件名
name:'index' //组件引用名
}
]
})
5、在app.vue中留坑<router-view></router-view>,Index.vue的内容就会展示到router-view这个容器里面
//app.vue中
<template>
<div>
<!-- 留坑,非常重要 -->
<router-view></router-view>
</div>
</template>
三、路由跳转
[一]、<router-link>基本属性
<router-link to="" tag="">主页</router-link>
(1)to属性表示绑定地址。to="/"
(2):to="",绑定动态路由,与data(){}中的变量进行绑定--详见下文[三]、动态路由。
绑定路由表中的name属性。:to="{name:路由表中name值}"
(3)tag属性表示以什么标签名显示,默认以a标签显示;tag=div表示将该标签以div呈现
(4)children:[],子路由在这里面配置,children:[{path:'/',component:xxx,name:xxx,cildren:[三级路由]},....]
[二]、路由跳转
1、跳转到上一次浏览的页面--this.$router.go(-1);
<template>
<div class="container">
<h1>home</h1>
<button @click="goToMenu" class="btn btn-success">just do it</button>
</div>
</template>
<script>
export default {
name: "Home",
methods:{
goToMenu(){
//跳转到上一次浏览的页面
this.$router.go(-1);
}
}
}
</script>
2、跳转到指定的页面--this.$router.replace('/about')
<template>
<div class="container">
<h1>home</h1>
<button @click="goToMenu" class="btn btn-success">just do it</button>
</div>
</template>
<script>
export default {
name: "Home",
methods:{
goToMenu(){
//指定跳转
this.$router.replace('/about')
}
}
}
</script>
3、跳转到指定路由的名字下--this.$router.replace({name:'nameValue'})
在router/index.js文件下,对Menu.vue组件进行name赋值
{
path:'/menu',
component:Menu,
name:'menuLink'
},
在Home.vue文件中
<template>
<div class="container">
<h1>home</h1>
<button @click="goToMenu" class="btn btn-success">just do it</button>
</div>
</template>
<script>
export default {
name: "Home",
methods:{
goToMenu(){
//跳转到指定路由的名字
this.$router.replace({name:'menuLink'})
}
}
}
</script>
4、通过this.$router.push()地址,或者name进行跳转
- 开发中这种方法最常用
<template>
<div class="container">
<h1>home</h1>
<button @click="goToMenu" class="btn btn-success">just do it</button>
</div>
</template>
<script>
export default {
name: "Home",
methods:{
goToMenu(){
//push地址跳转
this.$router.push('/menu')
//或者是通过name属性
//this.$router.push({name:'menuLink'})
}
}
}
</script>
[三]、动态路由
动态路由是将:to属性的值设置为data中的变量(:to="routerDemo"),将具体的路由地址赋值给变量
<li><router-link :to="homeLink">主页</router-link></li>
export default {
name: "Header",
data(){
return{
homeLink:'/'
}
}
}
</script>
[四]、以导航栏的实现来理解
此导航栏只使用了bootstrapcss样式,在index.html中插入
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
1、创建主页(Home)、菜单(OrderingGuide)、管理(Admin)、关于我们(about/About)、登录(Login)、注册(Register)组件
<!-- home组件,其余组件略过-->
<template>
<h1>home</h1>
</template>
<script>
export default {
name: "Home"
}
</script>
2、在src/router/index.js中配置路由
import Home from './components/Home'
import Menu from './components/Menu'
import Admin from './components/Admin'
import About from './components/about/About'
import Login from './components/Login'
import Register from './components/Register'
const router = new VueRouter({
mode:'history', //history模式,可以去除URL里面的hash符号(#)
routes:[ //注册组件路由,
{
path:'/',
component:Home,
},{
path:'/menu',
component:Menu
},{
path:'/admin',
component:Admin
},{
path:'/about',
component:About,
},{
path:'/login',
component:Login
},{
path:'/register',
component:Register
}
]
})
3、新建一个header.vue组件,用于写顶部导航栏
<template>
<header>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<!-- svg矢量图logo-->
<a class="py-2" href="#" aria-label="Product">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" class="d-block mx-auto" role="img" viewBox="0 0 24 24" focusable="false"><title>Product</title><circle cx="12" cy="12" r="10"></circle><path d="M14.31 8l5.74 9.94M9.69 8h11.48M7.38 12l5.74-9.94M9.69 16L3.95 6.06M14.31 16H2.83m13.79-4l-5.74 9.94"></path></svg>
</a>
<a href="/" class="navbar-brand">Pizza点餐系统</a>
<!-- 顶部 左侧-->
<ul class="navbar-nav">
<!-- navbar-nav去除li前面的小点-->
<li><router-link to="/" class="nav-link">主页</router-link></li>
<li><router-link to="/menu" class="nav-link">菜单</router-link></li>
<li><router-link to="/admin" class="nav-link">管理</router-link></li>
<li><router-link to="/about" class="nav-link">关于我们</router-link></li>
</ul>
<!-- 顶部-右侧-->
<ul class="navbar-nav ml-auto">
<!-- ml-auto实现两个li在顶部最右侧-->
<li><router-link to="/login" class="nav-link">登录</router-link></li>
<li><router-link to="/register" class="nav-link">注册</router-link></li>
</ul>
</nav>
</header>
</template>
<script>
export default {
name: "Header"
}
</script>
4、在app.vue中引入导航栏,以及为导航栏的导航组件(主页、菜单、管理等)留坑
<template>
<div id="app">
<!-- header导航栏组件将在这展示-->
<div class="container">
<app-header></app-header>
</div>
<!-- 为导航栏的导航组件(主页、菜单、管理等)留坑-->
<div class="container">
<router-view></router-view>
</div>
</div>
</template>
<script>
import Header from "./components/Header";
export default {
name: 'app',
components:{
//属性名:组件名
//属性名驼峰式命名的话 ,ES6会自动解析为app-header;如果属性名命名为app-header的话,必须使用引号
appHeader:Header,
}
}
</script>
[五]、路由嵌套
1、在router/index.js文件中配置一级、二级、三级路由
//一级路由
import About from './components/about/About'
//二级路由
import Contact from "./components/about/Contact";
import Delivery from "./components/about/Delivery";
import History from "./components/about/History";
import OrderingGuide from "./components/about/OrderingGuide";
//三级路由
import Person from "./components/about/contact/Person";
import Phone from "./components/about/contact/Phone";
{
path:'/about',
component:About,
name:'aboutLink',
redirect:'/about/history',//默认显示
children:[
{
path:'/about/contact',
name:'contactLink',
component:Contact,
children:[
{
path:'/phone',
name:'phoneNumber',
component:Phone
},{
path:'/person',
name:'person',
component:Person
},
]
},{
path:'/about/delivery',
name:'deliveryLink',
component:Delivery
},{
path:'/about/history',
name:'historyLink',
component:History
},{
path:'/about/orderingGuide',
name:'orderingGuideLink',
component:OrderingGuide
},
]
},
2、一级路由的vue文件
导航栏header组件在app.vue中使用
<template>
<div id="app">
<div class="container">
<!--使用header组件-->
<app-header></app-header>
</div>
<div class="container">
<!--header上的每一个按钮对应的vue文件内容将展示在此-->
<router-view></router-view>
</div>
</div>
</template>
<script>
import Header from "./components/Header";
export default {
name: 'app',
components:{
//属性名:组件名
//属性名驼峰式命名的话 ,ES6会自动解析为app-header;如果属性名命名为app-header的话,必须使用引号
appHeader:Header,//引用header组件
},
}
</script>
header组件内容
<template>
<header>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<!-- 顶部 左侧-->
<ul class="navbar-nav">
<!-- navbar-nav去除li前面的小点-->
<li><router-link to="/about" class="nav-link">关于我们</router-link></li>
</ul>
<!-- 顶部-右侧-->
</nav>
</header>
</template>
3、二级路由的vue文件
<template>
<div>
<div class="row mb-5">
<div class="col-4">
<!-- 导航router-link-->
<div class="list-group mb-5">
<router-link tag="li" class="nav-link" :to="{name:'historyLink'}">
<a class="list-group-item list-group-item-action">历史订单</a>
</router-link>
<router-link tag="li" class="nav-link" :to="{name:'contactLink'}">
<a class="list-group-item list-group-item-action">联系我们</a>
</router-link>
<router-link tag="li" class="nav-link" :to="{name:'orderingGuideLink'}">
<a class="list-group-item list-group-item-action">点餐</a>
</router-link>
<router-link tag="li" class="nav-link" :to="{name:'deliveryLink'}">
<a class="list-group-item list-group-item-action">快递信息</a>
</router-link>
</div>
</div>
<div class="col-8">
<!-- 留坑,三级路由的vue文件内容将展示在此。about路由下的两个子路由内容,点击后将展示在此-->
<router-view></router-view>
</div>
</div>
</div>
</template>
[六]、router-view复用,通过路由的方式重复使用同一个组件
1、在需要复用的路由下添加conponents属性
//src/router/index.js
{
path:'/',
component:Home,
name:'homeLink',
components:{ //需要复用的组件
'orderingGuide':OrderingGuide,
'delivery':Delivery,
'history':History
}
},
2、在需要复用组件的vue文件使用router-view-----未完待续
<!-- router-view复用-->
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-4">
<router-view name="orderingGuide"></router-view>
</div>
<div class="col-sm-12 col-md-4">
<router-view name="delivery"></router-view>
</div>
<div class="col-sm-12 col-md-4">
<router-view name="history"></router-view>
</div>
</div>
</div>
</div>
四、路由守卫
1、全局守卫
router.beforeEach((to,from,next)=>{
to:路由地址,即将要进入的目标 路由对象
from:路由地址,从哪一个路由离开
next:异步函数,决定展示页面
})
// 全局守卫
router.beforeEach((to,from,next)=>{
comsole.log(to);
//这里通常是判断store.getters.isLogin===false来确定是否登录
if(to.path == '/login' || to.path == '/register'){
next();
}else{
alert('未登录')
next('/login')
}
})
2、全局后置钩子
router.afterEach((to,from)=>{
to:路由地址,即将要进入的目标 路由对象
from:路由地址,从哪一个路由离开
})
3、路由独享守卫
beforeEnter:(to,from,next)=>{
//写在路由配置里面
}
{
path:'/admin',
component:Admin,
name:'adminLink',
beforeEnter:(to,from,next)=>{
alert('非管理员禁止进入');
if(to.path == '/login' || to.path == '/register'){
next();
}else{
alert('未登录')
next('/login')
}
}
},
4、组件内的守卫
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
}
(1)、beforeRouteEnter
beforeRouteEnter(to,from,next){
//会报错,Cannot read property 'name' of undefined
alert('查看现在能否拿到data内的数据'+this.name);
}
beforeRouteEnter 守卫 不能 访问 this,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。
不过,你可以通过传一个回调给 next来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。
beforeRouteEnter (to, from, next) {
next(vm => {
// 通过 `vm` 访问组件实例
alert('查看现在能否拿到data内的数据'+vm.name);
})
}
(2)、beforeRouteUpdate
待续.....
(3)、beforeRouteLeave
beforeRouteLeave(to,from,next){
alert('查看现在能否拿到data内的数据'+this.name)
if(confirm('确定离开吗???') == true){
next()
}else{
next(false)
}
}