需要解决的问题:
store存储登录状态
Vue-Router导航钩子拦截路由
Vue-Resource获取后台的数据
需要判断登录返回的user
源码参考
主要技术栈:Vuex + Vue-Resource + Vue-Router
后台用mock-data来模拟数据。
先来看一下效果图

第一步、起个项目打开控制台输入
$ npm install --global vue-cli#创建一个自己的基于webpack的新项目
$ vue init webpack my-project(这里是你自己的工程名)
$ cd my-project(进到你的工程文件夹下)
$ npm install (安装依赖)
$ npm run dev
注意:起工程的时候回让你选择ESLint,Test等等各种测试,这里都默认选no就可以。

现在你的项目应该跑起来了。打开控制台输入
npm run dev
应该是这样的。

好了起项目成功了,接下来撸起袖子加油干吧。
先来看一下项目结构:

第二步、配置一下mock-data。
{
"users": [
{
"id" : 1,
"username": "aaa",
"password": "aaa"
},
{
"id" : 2,
"username": "bbb",
"password": "bbb"
},
{
"id": 3,
"username": "ccc",
"password": "ccc"
}
]
}
这里给指定了三个用户名和密码,在login登陆的时候只有输入正确的用户名和密码才可以登陆实现页面的跳转。
第三步 配置view视图层Login.vue文件中
<script>
export default {
data() {
return {
name:'',
pwd:'',
error:''
}
},
computed: {
user() {
return this.$store.state.user
}
},
methods:{
isLogin:function() {
this.$http.get('http://localhost:3000/users?username='+this.name+'&password='+this.pwd).then((response) => {
//这里在isLogin方法中先判断一下后台返回的是否为空值,如果不是然后提交后台返回的值。
//注意这里是个难点,Vuex与Vue-Resource结合使用。
if(response.body != null & response.body.length > 0){
this.$store.commit('isLogin',response.body[0]);
this.name=''
this.pwd= ''
this.$router.push({ path: 'main' })
}else{
alert('请输入正确的用户名和密码!!!');
this.name=''
this.pwd= ''
}
}).then((error)=> this.error = error)
}
}
}
</script>
接下来是Main.vue ,这个页面很简单,简单的写一些内容作为测试是否登录跳转成功。
<template>
<div>
<h1>Hello Main!</h1>
<section v-show="user">
<!-- 这里的user是从下面JavaScript的computed的user()方法中得到的。 -->
<p>欢迎{{user.username}}</p>
</section>
</div>
</template>
<script>
export default {
computed: {
user(){
//因为在main.js中已经全局注册了store,所以这里直接用this.$直接使用。
return this.$store.state.user
}
}
}
</script>
下面来配置一下路由。routes.js
//先引入需要路由的文件
import Main from '../components/Main'
import Login from '../components/Login'
export default [
{
path: '/login',
component: Login
},
{
path: '/main',
meta: {
// 添加该字段,表示进入这个路由是需要登录的
requireAuth: true,
},
component: Main,
}
]
接下来是main.js(这里只对重点拿出来细说)
// 全局导航钩子
router.beforeEach((to, from, next) => {
// 判断该路由是否需要登录权限
if (to.meta.requireAuth) {
// 通过vuex state获取当前的token是否存在
// console.log(isEmptyObject(store.state.user))
if(!isEmptyObject(store.state.user)) {
next();
}
else {
next({
path: '/login',
query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
}
else {
next();
}
})
function isEmptyObject(obj) {
for (var key in obj) {
return false;
}
return true;
}
存在的问题及待解决的问题: 登陆数据存在store中,每次刷新页面都会没有了。接下来要用LocalStorage或者Cookie来保存数据。
欢迎大神纠察指正,也希望前端爱好者提出宝贵意见,一起学习,一块交流讨论。喜欢的话请点个赞吧。(感谢阅读)
网友评论