使用vue、vue-router实现登录功能 有token跳转至首页,没有token返回登录页面
<!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>
<script src="../js/vue.js"></script>
<script src="../js/vuex.js"></script>
<script src="../js/vue-router.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="../js/axios.js"></script>
<script src="../js/qs.js"></script>
</head>
<body>
<div id="app">
<router-view></router-view>
</div>
<script>
let qs = Qs;
let login = {
data() {
return {
loginData: {}
}
},
template: `
<div>
<h1>欢迎登陆</h1>
用户名:<input type="text" v-model="loginData.username">
密码:<input type="text" v-model="loginData.password">
<button @click="loginHandler">登录</button>
</div>
`,
methods: {
loginHandler() {
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios({
url: 'http://47.94.46.113:8888/user/login',
method: 'post',
data: JSON.stringify(this.loginData)
}).then(res => {
sessionStorage.setItem('token', res.data.data.token)
this.$router.push({ path: '/index' })
})
}
}
}
let index = {
data() {
return {}
},
template: `
<div>
<h1>欢迎使用</h1>
</div>
`
}
let router = new VueRouter({
routes: [
{ path: '/', redirect: '/login' },
{ path: '/login', component: login },
{ path: '/index', component: index },
]
})
router.beforeEach((to, from, next) => {
let token = sessionStorage.getItem('token');
if (to.path != '/login' && !token) {
alert('请先登录!');
next('/login')
}
next();
})
let vm = new Vue({
el: '#app',
data: {
},
methods: {
},
router
})
</script>
</body>
</html>