Browse Source

路由守卫

master
maochaoying 2 years ago
parent
commit
d4a3d7abce
  1. 11
      src/pages/Login.vue
  2. 19
      src/router/index.js

11
src/pages/Login.vue

@ -92,7 +92,7 @@
</template>
<script setup>
import { ref } from 'vue'
import { ref, onMounted } from 'vue'
import Back from '@/static/img/login/back.png'
import { DesktopIcon, LockOnIcon } from 'tdesign-icons-vue-next'
import { useRouter } from 'vue-router'
@ -119,13 +119,20 @@ const onSubmit = async ({ validateResult, firstError }) => {
accountStore.updateToken(res?.data?.token)
accountStore.updateUsername(res?.data?.username)
Cookie.setCookie('t', res?.data?.token)
router.push('/')
window.location.href = '/'
} else {
MessagePlugin.error({ content: '请输入正确的用户名和密码!' })
}
} else {
}
}
onMounted(() => {
const token = Cookie.getCookie('t')
if (token) {
window.location.href = '/'
}
})
</script>
<style lang="scss" scoped>

19
src/router/index.js

@ -1,11 +1,12 @@
import { createRouter, createWebHashHistory } from 'vue-router'
import Cookies from '@/utils/cookie'
const Home = () => import('@/pages')
const Login = () => import('@/pages/Login')
// 配置路由信息
const routes = [
{ path: '/', component: Home },
{ path: '/login', component: Login },
{ path: '/', component: Home, name: 'Home' },
{ path: '/login', component: Login, name: 'Login' },
]
const router = createRouter({
@ -13,4 +14,18 @@ const router = createRouter({
history: createWebHashHistory(),
})
const isAuthenticated = Cookies.getCookie('t')
router.beforeEach(async (to, from) => {
if (
// 检查用户是否已登录
!isAuthenticated &&
// ❗️ 避免无限重定向
to.name !== 'Login'
) {
// 将用户重定向到登录页面
return { name: 'Login' }
}
})
export default router
Loading…
Cancel
Save