上篇文章说完了整个项目搭建,现在来说一下Vue-router。(我表示996很开心,就是感觉时间很挤喽。)
一、编写router文件夹下的index.js
引入对应的页面(.vue文件)
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) //下面用了两种方式引入vue文件,建议选择未注释的。 后面会说到项目的优化。 //import index from '@/pages/index/index' const index = ()=>import('@/pages/index/index') const active = ()=>import('@/pages/active/active') const shopcart = ()=>import('@/pages/shopcart/shopcart') const mine = ()=>import('@/pages/mine/mine') const email = ()=>import('@/pages/email/email') const routes = [ {path:'/',name:'index',component:index,meta:{title:'首页',requireAuth:true}}, {path:'/active',name:'active',component:active,meta:{title:'活动页'}}, {path:'/shopcart',name:'shopcart',component:shopcart,meta:{title:'购物车'}}, {path:'/mine',name:'mine',component:mine,meta:{title:'我的'}}, {path:'/email',name:'email',component:email,meta:{title:'邮件'}}, {path:'*',name:'404',components:xxxx,meta:{title:'页面找不到喽'}} ] const router = new Router({ mode:"history", //mode为history时,需要后台配置一下,具体https://router.vuejs.org/zh/guide/essentials/history-mode.html#后端配置例子 routes, scrollBehavior (to, from, savedPosition) { // 如果是购物车页面scrollTop:100 // if(to.name == 'shopcart'){ // return {x:0,y:100} // } } }); /* 下面是路由的全局钩子函数 **/ //这是全局路由跳转前触发的函数 router.beforeEach((to,from,next)=>{ //可以做登录拦截。 需要登录的路由后面加上requireAuth:true 就可以 if(to.matched.some(r => r.meta.requireAuth)){ // You can do something } document.title = to.meta.title; next(); }) //这是全局路由跳转后触发的函数 router.afterEach((to,from)=>{ //不接受next函数,并且不能改变导航本身 })二、router-link的使用
router-link 跳转模式分为 push 和 replace,大家看一下下图:(PS:我前端不是切图仔!)
总结一下就是 replace跳转 会使当前页面出栈,目标页面入栈, push跳转会使当前页面和目标页面都入栈
