使用Vuex实现登陆成功后展示登录用户的信息

需求描述:

  在登录页面登陆成功之后,在系统首页(或者首页右上角)展示登陆者信息,如图:

登陆逻辑:

1、...mapActions(['saveUserName']):
  相当于将 `this.saveUserName(username)` 映射为 `this.$store.dispatch('saveUserName', username)`
2、在登陆时把用户名存入vuex中
 1 methods: {
 2     ...mapActions(['saveUserName']),
 3     login() {
 4       this.axios
 5         .post('/user/login', {
 6           username: this.username,
 7           password: this.password
 8         })
 9         .then(res => {
10           console.log('res')
11           console.log(res)
12           this.$cookie.set('userId', res.id, { expires: 7 })
13           this.$router.push('/#/index')
14         })
15     }
16   }
View Code

综上已经可以在首页右上角展示登录人的username了,但是页面刷新之后就不能正常显示了。

所以可以在APP.vue里在存入一次:

 1 <template>
 2   <div id="app">
 3     <router-view />
 4   </div>
 5 </template>
 6 <script>
 7 export default {
 8   name: 'app',
 9   data() {
10     return {}
11   },
12   mounted() {
13     if (this.$cookie.get('userId')) {
14       this.getUser()
15       this.getCartCount()
16     }
17   },
18   methods: {
19     getUser() {
20       this.axios.get('/user').then((res = {}) => {
21         this.$store.dispatch('saveUserName', res.username)
22       })
23     },
24     getCartCount() {
25       this.axios.get('/carts/products/sum').then((res = {}) => {
26         this.$store.dispatch('saveCartCount', res)
27       })
28     }
29   }
30 }
31 </script>
32 <style lang="scss">
33 @import './assets/scss/reset.scss';
34 @import './assets/scss/config.scss';
35 @import './assets/scss/mixin.scss';
36 @import './assets/scss/button.scss';
37 @import './assets/scss/modal2.scss';
38 </style>
View Code

3、在NavHeader组件里取出state里的username, 但是一定要用computed,因为页面展示完了可能值还没有取到,就导致无法显示登录人的username

computed: {
        username() {
            return this.$store.state.username
        }
    },
View Code
<div class="topbar-user">
                    <a href="javascript:;" v-if="username">{{username}}</a>
                    <a href="javascript:;" v-if="!username" @click="login">登陆</a>
                    <a href="javascript:;">我的订单</a>
                    <a href="javascript:;" class="my-cart" @click="goToCart">
                        <span class="icon-cart"></span>
                        购物车
                    </a>
                </div>
            </div>

原文地址:https://www.cnblogs.com/hahahakc/p/12790463.html