需求描述:
在登錄頁面登陸成功之后,在系統首頁(或者首頁右上角)展示登陸者信息,如圖:
登陸邏輯:
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 }
綜上已經可以在首頁右上角展示登錄人的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>
3、在NavHeader組件里取出state里的username, 但是一定要用computed,因為頁面展示完了可能值還沒有取到,就導致無法顯示登錄人的username

computed: { username() { return this.$store.state.username } },
<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>