完成前端页面路由守卫

This commit is contained in:
NagoColer 2023-04-11 22:43:10 +08:00
parent b03fb8fdb5
commit 1bca3653b1
6 changed files with 51 additions and 15 deletions

View File

@ -1,5 +1,18 @@
<script setup>
import {get} from "@/net";
import {useStore} from "@/stores";
import router from "@/router";
const store = useStore()
if(store.auth.user == null) {
get('/api/user/me', (message) => {
store.auth.user = message
router.push('/index')
}, () => {
store.auth.user = null
})
}
</script>
<template>

View File

@ -40,8 +40,11 @@
import {User, Lock} from '@element-plus/icons-vue'
import {reactive} from "vue";
import {ElMessage} from "element-plus";
import {post} from "@/net";
import {get, post} from "@/net";
import router from "@/router";
import {useStore} from "@/stores";
const store = useStore()
const form = reactive({
username: '',
@ -59,7 +62,12 @@ const login = () => {
remember: form.remember
}, (message) => {
ElMessage.success(message)
router.push('/index')
get('/api/user/me', (message) => {
store.auth.user = message
router.push('/index')
}, () => {
store.auth.user = null
})
})
}
}

View File

@ -1,4 +1,5 @@
import { createRouter, createWebHistory } from 'vue-router'
import {useStore} from "@/stores";
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
@ -30,4 +31,17 @@ const router = createRouter({
]
})
router.beforeEach((to, from, next) => {
const store = useStore()
if(store.auth.user != null && to.name.startsWith('welcome-')) {
next('/index')
} else if(store.auth.user == null && to.fullPath.startsWith('/index')) {
next('/')
} else if(to.matched.length === 0){
next('/index')
} else {
next()
}
})
export default router

View File

@ -1,12 +0,0 @@
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})

View File

@ -0,0 +1,9 @@
import {ref, computed, reactive} from 'vue'
import { defineStore } from 'pinia'
export const useStore = defineStore('store', () => {
const auth = reactive({
user: null
})
return { auth }
})

View File

@ -1,6 +1,6 @@
<template>
<div>
欢迎进入到学习平台
欢迎{{store.auth.user.username}}进入到学习平台
</div>
<div>
<el-button @click="logout()" type="danger" plain>退出登录</el-button>
@ -11,10 +11,14 @@
import {get} from "@/net";
import {ElMessage} from "element-plus";
import router from "@/router";
import {useStore} from "@/stores";
const store = useStore()
const logout = () => {
get('/api/auth/logout', (message) => {
ElMessage.success(message)
store.auth.user = null
router.push('/')
})
}