有時候急着學更多新知識會把最基礎的遺忘,以前使用PHP那會還知道表單序列化,最近通過form獲取裏面所有name屬性對應的控件值卻把document.getElementById('表單Id').serializeArray()給遺忘了,通過遍歷name屬性去獲取表單控件值-----勿忘初心
需求:之前項目大都是後臺進行最後的登錄接入,現在用了vue需要前端自己通過實現登錄頁面,以博客登錄爲例,登錄前界面如下:
進入首頁頭部如下
點擊登陸進入後臺給的鏈接登錄頁(注意這裏是後臺給了登陸頁面不是前端自己製作)
登錄後獲取用戶名進行顯示
主要知識:vue-Router + vuex+接口獲取
(1)使用vuex在store倉庫中存儲一個表示login的state變量,userInfo變量標誌用戶信息,使用vuecli的一般是在store.js中聲明
const state = {
userInfo:{"username":''},//其他用戶屬性可在這裏初始化
login: false//默認還沒登錄
}
(2)header.vue文件html代碼段
第一次進入頁面加載header的時候先進行一次判斷,判斷用戶是否已經登錄,如果已經登錄則將頭部用戶信息展示,否則直接顯示登錄按鈕
如何判斷用戶是否已經登錄?由於登錄頁面並不是前端自己製作,因此就需要後臺給個接口告訴前端用戶是否已經登錄,前端進行判斷,因此這個接口就是後臺所給的可以判斷用戶是不是已經登錄的接口,並且接口最好是返回一個status狀態值,如果已經登錄並將用戶信息返回~(header作爲公共頭部是一進來就加載,因此此處接口調用了一次);退出登錄只需將login值設置爲false即可直接退出登錄,監聽用戶是否登錄此處使用計算屬性返回login變量進行監聽
<template>
<div>
<div v-show="isLogin">
{{userInfo.username}}
<div @click="loginout" style="cursor:pointer;">退出登錄</div>
</div>
<div @click="login" style="cursor:pointer;" v-show="!isLogin">登錄</div>
</div>
</template>
<script>
export default {
data() {
return {
}
},
computed: {
isLogin(){
return this.$store.getters.getLogin
},
loginout(){
this.$store.state.login = false;window.location.href="登錄鏈接";
}
},
methods:{
login(){
window.location.href="登錄鏈接";
}
},
mounted(){
this.fetch({
url:'後臺給的判斷用戶是否已經登錄接口',
method:'post'
}).then(res=>{
if(res.status==200){
this.$store.state.login = true;//如果已經登錄將變量login設置爲true
this.$store.state.userInfo= res.data;//將後臺登錄後用戶信息給userInfo
}
})
}
}
</script>
(2)處理完剛進入頁面的情況,接着便是每一個路由進入要如何處理,由於'/home’路由爲進入頁面,無論登錄還是沒登錄都可以顯示,因此對'/home'路由不進行處理,其他路由遍歷統一控制,使用vue-router,beforEach鉤子函數,在遍歷之前先用vuex寫一個mutations函數對路由進行處理,思路是,對每個路由請求後臺所給的判斷用戶是否已經登錄的接口,如果已經登錄,則跳轉到當前路由,如果未登錄,則跳轉到登錄頁面鏈接進行登錄,mutations如下:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios';
const mutations = {
updateUserinfo(state, to) {
axios.post('判斷用戶是否已經登錄接口').then((res) => {
if(res.data.status==200){
//已經登錄,login設置爲true,跳轉到當前路由
state.userInfo = res.data.data;
state.login = true;
router.push(to);
}else{
//未登錄,跳轉到登錄頁面
toast['error']({
msg: res.data.statustext,
timeout: 3000
});
window.location.href = "後臺所給登錄頁面鏈接";
}
}).catch((err) => {
console.log("err",err);
toast['error']({
msg: '獲取用戶信息失敗!',
timeout: 3000
});
window.location.href = "後臺所給登錄頁面鏈接";
})
}
}
(3)最後一步,路由遍歷
router.beforeEach((to, from, next) => { //切換網頁標題
//to要跳轉過去的路由,from當前要離開的路由,next進行頁面跳轉必須調用,否則不會跳轉到下一個路由
if(!store.state.login&&to.path!='/home'){
//還沒登錄並且當前頁面不是首頁(首頁已經在第一步進行了處理)
store.commit('updateUserinfo',to);//調用mutation路由處理函數
}else{
//已經登錄了,如果路由匹配不上,跳轉到404錯誤組件頁面(該組件自己編寫^_^)
if(to.matched.length===0){
next({path:'/404'});//轉至404
}else{
//正確路由,next()進入到要跳轉路由
document.title = '';//設置進入頁面title
next();
}
}
});
總結:
一個接口:後臺給出如getUserInfo接口,該接口返回用戶是否已經登錄,基本接口返回如下res{status:200,data:{username:'xxxx','images':'xxx'}}
Vue-Router:router.beforeEach()鉤子函數
Vuex:存儲判斷用戶登錄信息{login:false,userInfo:{username:''}}
(最後,發現該方法存留一個不容易發現的bug,當刷新當前頁面點擊瀏覽器的回到上一步(即返回鍵)時,會跳轉不過去。。。這是爲什麼呢。。。)