<!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> <router-link to="/a">A</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: "/a", meta:{ login_required:false }, component: { template: ` <h1>A</h1> ` } }, { path: "/post", meta:{ login_required:true }, component: { template: ` <h1>帖子管理</h1> <router-link to="/rain" append>点击you惊喜</router-link> <router-view></router-view> ` }, children:[ { path:"rain", component:{ template:"<h1>内涵段子</h1>" } } ] }, ]; var router = new VueRouter({ routes: routes }); router.beforeEach(function (to,from ,next) { //类似于中间件 ,访问之前做判断 var logged_in = true; //用户未登录状态 if(!logged_in && to.match(function (item) { return item.meta.login_required })) //如果用户未登录且要跳转到post页面 next("/login"); else next() //正常执行 }); router.afterEach(function (to,from) { //执行完之后要执行的函数 }) new Vue({ el: "#app", router: router })