<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script src="node_modules/vue/dist/vue.js"></script>
<script src="node_modules/vue-router/dist/vue-router.js"></script>
<script>
Vue.use(VueRouter);
var Login = {
data() {
return {
name: '',
pwd: ''
}
},
template: `
<div>
<input type="text" v-model="name" />
<input type="password" v-model="pwd" />
<input type="button" value="登录" @click="loginHandler" />
</div>
`,
methods: {
loginHandler() {
// 用户名、密码存储在本地内存中
localStorage.setItem('user', {name: this.name, pwd: this.pwd});
// 保存后跳转到博客页面
// 编程式导航
this.$router.push({
name: 'blog'
});
}
}
}
var Home = {
template: `
<div>首页内容</div>
`
};
var Blog = {
template: `
<div>博客内容</div>
`
};
var router = new VueRouter({
routes: [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/blog',
name: 'blog',
component: Blog,
// 权限控制:跳转到博客页面时验证是否已登录
meta: {
// true的时候是未登录状态
requiresAuth: true
}
},
{
path: '/login',
// name: 'login',
component: Login
}
]
});
// 全局导航守卫
router.beforeEach((to, from, next)=>{
console.log(to);
console.log(from);
if (to.meta.requiresAuth) {
// 如果localStorage中有user,直接放行到blog
if(localStorage.getItem('user')) {
next();
} else {
next({
path: '/login'
// 或者使用命名路由
// name: 'login'
});
}
} else {
// 放行
next();
}
});
var App = {
template: `
<div>
<!-- 声明式导航 -->
<router-link to="/home">首页</router-link>
<router-link to="/blog">博客</router-link>
<router-view></router-view>
</div>
`
}
new Vue({
el: '#app',
template: `
<App />
`,
components: {
App
},
router
});
</script>
</body>
</html>