做的时候遇到一个问题,就是在Login.vue中输入正确的用户名和密码并跳转到Main.vue,发现并没有更新用户登录状态,我只是在created中设置了http请求。后面我增加了事件提交才解决的。
Login.vue
doLogin(){
//console.log(this.$http.post);
this.$http.post('http://localhost/wyyx/user.php',
{uname:this.uname,upwd:this.upwd},{emulateJSON:true,withCredentials:true}).then(
(response)=>{
//console.log(response.body);
if(response.body.ok==1){
sessionStorage.isLogin = 0;
sessionStorage.uname = this.uname;
this.$emit('doLogin',this.uname);
this.$router.push('/');
}else{
this.$router.push('/login');
}
});
},
Main.vue
<router-view @doLogin="doLogin"></router-view>
created:function(){
console.log("created");
//console.log(this.$http.get);
this.$http.get("http://localhost/wyyx/isLogin.php",{emulateJSON:true,withCredentials:true}).then((response)=>{
console.log("11111");
console.log(response.body);
if(response.body.ok==1){
this.lrShow=0;
this.uname=response.body.uname;
}else{
this.lrShow=1;
this.uname='';
}
});
},
doLogin(userName){
this.lrShow=0;
this.uname=userName;
},
logout(){
console.log("logout");
sessionStorage.isLogin = 1;
sessionStorage.uname = '';
this.lrShow=1;
this.$http.get("http://localhost/wyyx/logout.php",{emulateJSON:true,withCredentials:true}).then((response)=>{
console.log(response.body);
})
}
需要注意的是,子组件向父组件是通过事件提交实现的,并且在父组件router-view上声明事件
参考链接:
本来还以为要用到vuex,后面发现并不需要