在線商城項目16-頭部前端邏輯修改

簡介

頭部右側(cè)之前有三個按鍵如下:



這是不合理的,我們應(yīng)該根據(jù)登錄態(tài)來做一個區(qū)別顯示。未登錄情況下顯示login和購物車圖標。已登錄情況下顯示用戶名,logout,購物車圖標。

本節(jié)有如下主要任務(wù):

  1. 將用戶信息作為全局狀態(tài)進行管理
  2. 處理登入時的頭部前端邏輯
  3. 處理登出頭時的部前端邏輯

1. 將用戶信息作為全局狀態(tài)進行管理

頭部是公共組件,我們要求在所有引入頭部組件頁面中,都能根據(jù)用戶態(tài)區(qū)別顯示。那么我們需要將用戶信息作為全局狀態(tài)進行管理.
step1 引入vue的全局狀態(tài)管理器vuex。

npm install vuex --save

step2 新建store目錄如下:



user.js

const user = {
  state: {
    isLogin: false,
    userName: ''
  },
  mutations: {
    LOG_IN: (state, payload) => {
      state.isLogin = true
      state.userName = payload.userName
    },
    LOG_OUT: (state, payload) => {
      state.isLogin = false
      state.userName = ''
    }
  }
}

export default user

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    user
  }
})

export default store

step3 在main.js中引入store

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import VueLazyLoad from 'vue-lazyload'

import './assets/css/base.css'
import './assets/css/login.css'
import './assets/css/product.css'

Vue.config.productionTip = false

Vue.use(VueLazyLoad, {
  loading: '../static/loading/loading-bars.svg',
  error: '../static/ok-2.png'
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

2. 處理登入時的頭部前端邏輯

step1 修改PageHeader.vue邏輯如下

<template>
  <header class="header">
    <div class="navbar">
      <div class="navbar-left-container">
        <a href="/">
          <img class="navbar-brand-logo" src="../assets/logo.png"></a>
      </div>
      <div class="navbar-right-container" style="display: flex;">
        <div class="navbar-menu-container">
          <!--<a href="/" class="navbar-link">我的賬戶</a>-->
          <span class="navbar-link">{{user.userName}}</span>
          <a href="javascript:void(0)" class="navbar-link" v-if="!user.isLogin" @click="toPageLogin">Login</a>
          <a href="javascript:void(0)" class="navbar-link" v-else>Logout</a>
          <div class="navbar-cart-container">
            <span class="navbar-cart-count"></span>
            <a class="navbar-link navbar-cart-link" href="/#/cart">
              <svg class="navbar-cart-logo">
                <symbol id="icon-cart" viewBox="0 0 38 32">
                  <title>cart</title>
                  <path class="path1"
                        d="M37.759 0h-4.133c-0.733 0.004-1.337 0.549-1.434 1.255l-0.546 4.342c-0.081 0.484-0.496 0.849-0.997 0.849-0.005 0-0.009-0-0.014-0h-27.604c-0.003 0-0.007-0-0.011-0-1.674 0-3.031 1.357-3.031 3.031 0 0.34 0.056 0.666 0.159 0.971l2.52 8.062c0.385 1.194 1.486 2.043 2.785 2.043 0.126 0 0.25-0.008 0.372-0.023l22.983 0.002c0.515 0.131 0.626 0.768 0.626 1.283 0.005 0.044 0.009 0.095 0.009 0.146 0 0.501-0.294 0.933-0.718 1.134l-22.439 0.003c-0.354 0-0.642 0.287-0.642 0.642s0.287 0.642 0.642 0.642h22.745l0.131-0.071c0.919-0.392 1.551-1.287 1.551-2.33 0-0.058-0.002-0.116-0.006-0.173 0.021-0.108 0.033-0.24 0.033-0.376 0-1.072-0.732-1.973-1.724-2.23l-23.357-0.004c-0.063 0.008-0.135 0.013-0.209 0.013-0.719 0-1.332-0.455-1.566-1.093l-2.53-8.095c-0.048-0.154-0.076-0.332-0.076-0.515 0-0.973 0.782-1.764 1.752-1.778h27.657c1.159-0.004 2.112-0.883 2.232-2.011l0.547-4.345c0.010-0.083 0.078-0.147 0.161-0.152l4.133-0c0.354 0 0.642-0.287 0.642-0.642s-0.287-0.642-0.642-0.642z"></path>
                  <path class="path2"
                        d="M31.323 9.69c-0.022-0.003-0.048-0.004-0.074-0.004-0.328 0-0.598 0.248-0.633 0.567l-0.809 7.268c-0.003 0.022-0.004 0.048-0.004 0.074 0 0.328 0.248 0.598 0.567 0.633l0.074 0c0.001 0 0.003 0 0.004 0 0.327 0 0.596-0.246 0.632-0.563l0.809-7.268c0.003-0.022 0.004-0.048 0.004-0.074 0-0.328-0.248-0.598-0.567-0.633z"></path>
                  <path class="path3"
                        d="M27.514 25.594c-1.769 0-3.203 1.434-3.203 3.203s1.434 3.203 3.203 3.203c1.769 0 3.203-1.434 3.203-3.203s-1.434-3.203-3.203-3.203zM27.514 30.717c-1.060 0-1.92-0.86-1.92-1.92s0.86-1.92 1.92-1.92c1.060 0 1.92 0.86 1.92 1.92s-0.86 1.92-1.92 1.92z"></path>
                  <path class="path4"
                        d="M9.599 25.594c-1.769 0-3.203 1.434-3.203 3.203s1.434 3.203 3.203 3.203c1.769 0 3.203-1.434 3.203-3.203s-1.434-3.203-3.203-3.203zM9.599 30.717c-1.060 0-1.92-0.86-1.92-1.92s0.86-1.92 1.92-1.92c1.060 0 1.92 0.86 1.92 1.92s-0.86 1.92-1.92 1.92z"></path>
                </symbol>
                <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-cart"></use>
              </svg>
            </a>
          </div>
        </div>
      </div>
    </div>
  </header>
</template>

<script>
import { mapState } from 'vuex'

export default {
  computed: {
    ...mapState([
      'user'
    ])
  },
  methods: {
    // 跳轉(zhuǎn)登錄頁
    toPageLogin () {
      this.$router.push({ path: '/login', query: { redirect: this.$route.fullPath } })
    }
  }
}
</script>

step3 修改Login.vue
改動如下邏輯:

axios.post('/api/users/login', queryObj).then(res => {
        let data = (res && res.data) || {}
        if (data.code === '000') {
          let result = data.result || {}
          this.$store.commit('LOG_IN', {userName: result.userName})
          if (this.$route.query.redirect) {
            this.$router.push(this.$route.query.redirect)
          } else {
            this.$router.push('/')
          }
        } else {
          alert(`err:${data.msg || '系統(tǒng)錯誤'}`)
        }
      })

此時嘗試運行,能正常跳轉(zhuǎn)到登錄頁,但是輸入第一遍用戶名和密碼時,并沒有跳轉(zhuǎn),第二遍才跳轉(zhuǎn)。因為這里button在form內(nèi),默認會執(zhí)行submit??梢院唵蔚卦谠揵utton中添加'type= button',也可以將button挪到form外,不過此時userName和userPwd為空不再有提示,需要我們補充提示邏輯。重新修改Login.vue如下:

<template>
  <div class="login">
    <div class="logo">
      <h1>weleome to six-tao</h1>
    </div>
    <form action="">
      <div class="item">
        <label for="userName">賬號:</label>
        <input type="text" placeholder="Username" v-model="userName" id="userName"/>
      </div>
      <div class="item">
        <label for="userPwd">密碼:</label>
        <input type="userPwd" placeholder="userPwd" v-model="userPwd" id="userPwd"/>
      </div>
      <div class="item err-tip" v-show="errTip">
        <label>提示:</label>
        <span>{{errTip}}</span>
      </div>
    </form>
    <div class="btn-wraper">
      <button id="loginButton" @click="login">登錄</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  data () {
    return {
      userName: '',
      userPwd: '',
      errTip: ''
    }
  },
  methods: {
    login () {
      if (!this.userName || !this.userPwd) {
        this.errTip = '用戶名和密碼不能為空'
        return
      }
      this.errTip = ''
      let queryObj = {
        userName: this.userName,
        userPwd: this.userPwd
      }
      axios.post('/api/users/login', queryObj).then(res => {
        let data = (res && res.data) || {}
        if (data.code === '000') {
          let result = data.result || {}
          this.$store.commit('LOG_IN', {userName: result.userName})
          if (this.$route.query.redirect) {
            this.$router.push(this.$route.query.redirect)
          } else {
            this.$router.push('/')
          }
        } else {
          alert(`err:${data.msg || '系統(tǒng)錯誤'}`)
        }
      })
    }
  }
}
</script>

<style scoped>
  .login {
    font-size: 12px;
    position: fixed;
    width: 300px;
    height: 240px;
    background-color: lightcyan;
    border-radius: 10px;
    padding: 10px 20px 10px 10px;
    margin-top: -120px;
    margin-left: -150px;
    top: 50%;
    left: 50%;
  }
  .item {
    display: flex;
    align-items: center;
    margin-top: 20px
  }
  .item label {
    width: 60px;
    font-size: 1.2em;
  }
  .item input {
    flex: 1;
    height: 40px;
    line-height: 40px;
  }
  .btn-wraper {
    display: flex;
    justify-content: center;
  }
  .err-tip {
    margin-top: 5px;
    color: red;
  }
  #loginButton {
    width: 100px;
    color: #85592e;
    margin-left: auto;
    margin-right: auto;
    margin-top: 30px;
    background: yellow;
    border-radius: 5px;
    border: 1px solid gray;
    font-size: 1.2em;
  }
  .logo {
    text-align: center;
  }
</style>

此時,我們再來運行一遍:


3. 處理登出時的頭部前端邏輯

修改PageHeader.vue以下兩處:

<a href="javascript:void(0)" class="navbar-link" v-else @click="logout">Logout</a>

logout () {
      this.$store.commit('LOG_OUT')
}

總結(jié)

這一節(jié)我們從前端角度完成了登入登出的頭部前端邏輯。但是仍然還有一些問題,下一節(jié)我們繼續(xù)來完善。
提交一下代碼:
six-tao

git status
git diff
git add .
git status
git commit -am 'head logic changes to fit login'
git push
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 22年12月更新:個人網(wǎng)站關(guān)停,如果仍舊對舊教程有興趣參考 Github 的markdown內(nèi)容[https://...
    tangyefei閱讀 35,412評論 22 257
  • 哪些是淺嘗輒止? 哪些是長久投資? 哪些是興趣? 哪些是事業(yè)? 職業(yè)這么多,大家都想成為slash,究竟先做什么再...
    小俠不是仙閱讀 173評論 0 0
  • 今年有一個商業(yè)巨變時代的建議,里面提到一句話:“如果有人給你在火箭上提供了一個位置,那么,別管位置好壞,先上去再說...
    門前另一顆梨樹閱讀 244評論 0 1
  • 很久沒有玩英雄聯(lián)盟這個游戲了,從前在游戲里覺得很有成就的事比如五殺比如排位賽十幾連勝我也沒什么印象了。讓我時不時記...
    花心大魔王閱讀 296評論 0 2

友情鏈接更多精彩內(nèi)容