I'm currently practicing VueJs and making some sample apps. i'm making a very simple app that is basically just a login page where users will put their credentials and access their profile. However I can't think of a way to restrict view to the profile section if the user isn't logged (i.e that they try to access by manually changing the url to /profile)
The app is pretty barebones, it's just using JS and bootstrap.
Is there a way to immediately redirect users back to the login screen if they're not logged and try to access the profile page?
Vuex is a state management pattern for vue. js. $t is the injected method from vue. js or Vue.
Under the hood Vue will walk through all the properties that we define into the data and converts them to getter/setters using Object. defineProperty. When any data property gets a new value then the set function will notify the Watchers. A Watcher is created for each component when a Vue application is initialized.
You can use https://router.vuejs.org/guide/advanced/navigation-guards.html beforeEach
to check if the current user is logged or not and do what you need to do :).
your routes:
...
{
path:'/profile',
meta:{guest:false},
component:ProfileComponent
},
...
example :
router.beforeEach((to, from, next) => {
if (!to.meta.guest) {
// check if use already logged
// if true then go to home
return next({path:'/'}); // '/' is home page for example
// else then continue to next()
}
return next();
});
You can use also beforeEnter
param if you have only few routes which should be protected.
routes.js
import {ifAuthenticated} from "../middleware/authentication";
{
path: '/test',
name: 'Test',
component: Test,
beforeEnter: ifAuthenticated
},
authentication.js
import store from '../../store'
export const ifAuthenticated = (to, from, next) => {
store.dispatch('User/getUser')
.then(() => {
next()
})
.catch(() => {
next({ name: 'Login', query: { redirect_to: to.fullPath } })
})
}
Example with usage of vuex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With