VueX+VueRouter+Cookie實現簡單登入頁
阿新 • • 發佈:2021-08-03
路由頁的登入導航守衛設定
router.beforeEach((to, from, next) => { if (to.matched.some(m => m.meta.auth)) { // 對路由進行驗證 if (store.state.userInfo.isLogin==='100') { // 已經登陸 next() // 正常跳轉到你設定好的頁面 } else { // 未登入則跳轉到登陸介面,query:{ Rurl: t o.fullPath} // 表示把當前路由資訊傳遞過去方便登入後跳轉回來; next({ path: '/login', query: { Rurl: to.fullPath } }) } } else { next() } })
引入js-cookie
npm i js-cookie
模組化開發時:
import Cookies from 'js-cookie'
VueX中的設定
import Vue from 'vue' import Vuex from 'vuex' import Cookies from 'js-cookie' Vue.use(Vuex) const store = new Vuex.Store({ state: { userInfo: {name:'',isLogin:''} || Cookies.get('userInfo'), isLogin: 0, currentUser: '' }, mutations: { loginSuc(state,data){ state.userInfo=data
//快取2小時,1msx1000=1s,1sx60=1min,1minx60x2=2hours var date = new Date((new Date().getTime()+120*60*1000)) Cookies.set('userInfo',data,{expires:date}) }, loginOut(state) { state.userInfo = null Cookies.remove('userInfo'); } } }) export default store
登入頁登入邏輯部分
handleLogin() { var name = this.loginForm.username; this.$message({ message: "歡迎 " + name + ",(*^_^*)", center: true, }); this.$refs.loginForm.validate((valid) => { if (valid) { this.userInfo.name = name; this.userInfo.isLogin = "100"; this.$store.commit("loginSuc", this.userInfo); const url = this.$route.query.Rurl || "/"; this.$router.push(url); } else { console.log("error submit!!"); return false; } }); },
注:commit提交到store裡一次最多提交2個,多了會報錯