Inheritance above, this is a success and we should log into the main interface, and this time we should be able to display the login user's personal information. This time to use the vuex.
- User information is automatically logged
vuex guide is as follows:
Detailed omitted code (I'm too lazy to write), details at the source file store.
Note that when you can goto realize display user information, binding userInfo.
<template> <div id="home"> <i class="el-icon-user-solid"></i> <div>{{userInfo.name ? userInfo.name : userInfo.phone}}</div> <el-button type="danger" @click="logout">退出登录</el-button> </div> </template> <script> import {mapState} from 'vuex' export default { name: "home", computed: { ...mapState(['userInfo']) }, ..... <script>
But this time will find a problem, the information is refreshed when vuex storage will disappear, then we need to use a long login express-session limit in nodejs.
app.js in
app.use (the session ({ Secret: '12345' , cookie: {maxAge: 1000 * 60 * 60 * 24}, // set maxAge is 80000ms, i.e. after 80s session failure and the cookie expires Resave: to false , saveUninitialized: to true , }));
index.js in
/ * The sesion the userid, query corresponding User * / router.get ( '/ UserInfo', function (REQ, RES) { // remove the userid const the userid = req.session.userid // query UserModel.findOne ({ _id: userid}, _filter, function (ERR, the User) { // If not, return error IF (! the User) { // Clear saved browser userid of the cookie the Delete req.session.userid res.send ({code : . 1, MSG: 'please login' }) } the else { // if there is, return to User res.send ({code: 0 , Data: User}) } }) })
Then we returned to the front desk, in home.vue write on mounted, the page is refreshed when getUserInfo request.
mounted(){ this.getUserInfo() }, methods:{ ...mapActions(['getUserInfo']), logout(){ sessionStorage.removeItem("Flag") this.$router.push('/login') this.$store.dispatch("userLogin", false); this.$store.dispatch('logout') }, },
When a long time is exceeded, exit the current page back to the login page.
In the action.js
// 异步获取用户信息 async getUserInfo({commit}) { const result = await reqUserInfo() if (result.code === 0) { const userInfo = result.data commit(RECEIVE_USER_INFO, {userInfo}) }else { console.log(result.msg) sessionStorage.removeItem("Flag") router.push('/login') } },
- After setting be logged in to enter the Home
Set the routing guard, used router.beforeEach.
Here set the reference Click
Finally, attach the source address: https: //github.com/xinhua6/login.git