I'm using NativeScript-Vue.
I have some pages that are protected (member-only). And I maintain my user's login data in localstorage. I have two questions:
When a user opens the app, where in the application should we write the code to retrieve user's login data. I would like to read the data from the local storage and populate it in Vuex store. I know how to read data from localstorage but I don't know where/when I should do it so that user is logged in to begin with.
There are a few pages which are protected (member only). For these users, I want to show them the page content if they are logged in (based on vuex store), but if they are not logged in, I want them to be navigated to a login page. Again I am confused about where this code/condition should be written.
Any help is appreciated.
For navigating through components you can also use meta
key in the route object.
Example:
import VueRouter from 'vue-router'
const routes = [
{
path: '/',
name: 'home',
component: MainWindow,
meta: {
requiresAuth: true,
}
},
{
path: '/login',
name: 'login',
component: Login,
meta: {
guest: true
}
}
]
const Router = new VueRouter({
routes,
mode: 'history',
});
Router.beforeEach((to, from, next) => {
const userData = localStorageAuth.getUserData();
if (to.matched.some(record => record.meta.requiresAuth)) {
if (userData.token === null) {
next({
path: '/login',
params: {nextUrl: to.fullPath}
})
} else {
next();
}
});
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