<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <div> <router-link to="/">首页</router-link> <router-link to="/login">用户登录</router-link> <router-link to="/post">帖子管理</router-link> </div> <div> <router-view></router-view> </div> </div> <script src="../../lib/vue.js"></script> <script src="../../lib/vue-router.js"></script> <script src="js/main.js"></script> </body> </html>
var routes = [ { path: "/", component: { template: ` <h1>首页管理</h1> ` } }, { path: "/login", component: { template: ` <h1>用户登录</h1> ` } }, { path: "/post", component: { template: ` <h1>帖子管理</h1> ` } }, ]; var router = new VueRouter({ routes: routes }); router.beforeEach(function (to,from ,next) { //类似于中间件 ,访问之前做判断 var logged_in = false; //用户未登录状态 if(!logged_in && to.path == "/post") //如果用户未登录且要跳转到post页面 next("/login"); else next() //正常执行 }); router.afterEach(function (to,from) { //执行完之后要执行的函数 }) new Vue({ el: "#app", router: router })