Vue authentication
P粉765684602
P粉765684602 2023-08-18 10:33:04
0
1
579
<p>I'm building this little app using Vue, but I can't get the authentication to work. To be precise, the redirect doesn't work, I get both true and Authenticated logs, but I'm not redirected to the homepage (/). But when I open the app I am immediately taken to /login which is ok and I would like that too but as I said when I try to log in I am not redirected. </p> <p>This is my login component and router. </p> <pre class="brush:php;toolbar:false;">import { createRouter, createWebHistory } from 'vue-router' import LoginView from '@/views/LoginView.vue' import AboutView from '../views/AboutView.vue'; import isAuthenticated from '@/views/LoginView.vue'; const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/login', name: 'Login', component: LoginView }, { path: '/', name: 'Home', meta: { requiresAuth: true }, component: AboutView, beforeEnter:(to,_,next)=>{ if(to.meta.requiresAuth && !isAuthenticated.value){ next('/login'); } else{ next(); router.push('/'); } } } ] }) export default router</pre> <pre class="brush:php;toolbar:false;"><template> <div> <h2>Enter access token to log in</h2> <hr /> <div class="col-md-8"> <section id="loginForm"> <form @submit.prevent="checkAccessToken"> <div class="form-group"> <label><b>Access Token</b></label> <input v-model="accessToken" type="password" class="form-control" /> </div> <input type="submit" value="Login" class="btn btn-primary" /> </form> </section> </div> </div> </template> <script setup lang="ts"> import { ref} from 'vue' import router from '@/router/index' const isAuthenticated = ref(false); const accessToken = ref(''); const checkAccessToken = () => { if (accessToken.value === '123') { isAuthenticated.value = true; console.log(isAuthenticated.value); console.log('verified'); router.push('/'); } else { } }; </script></pre> <p><br /></p>
P粉765684602
P粉765684602

reply all(1)
P粉141455512

If onlyrouter.push()does not work

Then try to use an import method similar to vue-router

import { useRouter } from 'vue-router'
const router = useRouter();

Then use router.push('/')

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template