<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!--
login?ReturnUrl=https://vip.jd.com/home.html
login?ReturnUrl=https://order.jd.com/center/list.action
-->
<div id="app">
<router-view></router-view>
</div>
<script src="../vue.js"></script>
<script src="../vue-router.js"></script>
<script>
const Index = {
template: `
<div>
<h3>首页</h3>
<router-link to="/login">登录</router-link>
<router-link to="/order">我的订单</router-link>
<router-link to="/user">个人中心</router-link>
<router-link to="/vip">会员中心</router-link>
</div>
`
}
const Order = {
template: `
<div>我的订单</div>
`
}
const User = {
template: `
<div>个人中心</div>
`
}
const Vip = {
template: `
<div>会员中心</div>
`
}
const Login = {
template: `
<div>登录
<button @click="login">登录</button>
</div>
`,
methods: {
login () {
localStorage.setItem('ticket', 1)
// 要根据当前url中的query参数 returnURL进行路由的跳转
const url = this.$route.query.returnURL
// console.log(url)
// 利用js实现页面的跳转操作
this.$router.push(url)
}
}
}
const routes = [
{
path: '/',
component: Index
}, {
path: '/order',
component: Order,
meta: {
auth: true
}
}, {
path: '/user',
component: User,
meta: {
auth: true
}
}, {
path: '/vip',
component: Vip,
meta: {
auth: true
}
}, {
path: '/login',
component: Login
}
]
const router = new VueRouter({
routes
})
// 设置导航守卫
router.beforeEach((to, from, next) => {
// 判断路由对象中的matched是否有一个对象包含meta
if (to.matched.some(route => route.meta.auth)) {
if (localStorage.getItem('ticket')) {
next()
}else {
next('/login?returnURL=' + to.path) // 跳转时需要在url后添加一个query参数,参数值为要返回的url路径
}
} else {
next()
}
})
const app = new Vue({
el: '#app',
router
})
</script>
</body>
</html>