Below is the code that I have in my router/index.js
Vue.use(Router)
let router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld,
meta: {
guest: true
}
},
{
path: "/login",
name: "login",
component: LoginComponent,
meta: {
guest: true
}
},
{
path: "/secure",
name: "secure",
component: SecureComponent,
meta: {
requiresAuth: true
}
},
{
path: "/kelas",
name: "kelas",
component: KelasComponent,
meta: {
requiresAuth: true
}
}
]
})
router.beforeEach((to, from, next) => {
const record = to.matched.some(record => record.meta.requiresAuth);
console.log("record: ")
console.log(record)
if(record) {
console.log(localStorage.getItem('jwtToken'))
if (localStorage.getItem('jwtToken') == null) {
next({
path: '/login',
params: { nextUrl: to.fullPath }
})
} else {
next()
}
} else if(to.matched.some(record => record.meta.guest)) {
if(localStorage.getItem('jwtToken') == null){
next()
}
else{
next()
}
}else {
next()
}
})
export default router
And in my components/Login.vue I have something like below:
<template>
<section id="login">
<h1>Login</h1>
<form #submit="onSubmit">
<b-field label=""
type="is-warning"
message="Please enter a valid email">
<b-input type="email" name="email" v-model="input.email" placeholder="E-mail"></b-input>
</b-field>
<b-field label=""
type="is-warning"
message="Please enter your password">
<b-input type="password" name="password" v-model="input.password" placeholder="Password"></b-input>
</b-field>
<input type="password" name="password" v-model="input.password" placeholder="Password" />-->
<b-field :message="errors"
type="is-danger"
name="errors"
>
<!--<button type="button" v-on:click="login()" class="button">Login</button>-->
<button type="submit" class="button">Login</button>
</b-field>
</form>
</section>
</template>
<script>
import axios from 'axios'
export default {
name: 'Login',
data () {
return {
input: {
email: "",
password: ""
},
result : "",
errors: []
}
},
methods: {
onSubmit (evt) {
evt.preventDefault()
if(this.input.email != "" && this.input.password != "") {
axios.post('http://localhost:8081/api/auth/login', this.input)
.then(response => {
localStorage.setItem('user',JSON.stringify(response.data.user))
localStorage.setItem('jwtToken', response.data.token)
if (localStorage.getItem('jwtToken') != null){
this.$emit("authenticated", true)
this.$emit('loggedIn')
if(this.$route.params.nextUrl != null){
this.$router.push(this.$route.params.nextUrl)
}
else {
this.$router.push('secure')
}
}
})
.catch(e => {
console.log(e.response)
if(e.response.status === 401) {
this.errors.push("Invalid login")
}else{
this.errors.push(e)
}
})
} else {
this.result = "An email and password must be present"
console.log("An email and password must be present")
}
}
}
}
</script>
My codes above works very well. In secure.vue page, I can click a button which opens up kelas.vue page without any problem. But when I tried to refresh the page secure or kelas, it will push me back to page login.
From doing console.log, I can see that the values for jwttoken and to.matched.some(record => record.meta.requiresAuth); are still there; the only difference is when I do a reload, the from at this line router.beforeEach((to, from, next) => { becomes null.
Is there any way I can make the user to be still logged in after the user do a page reload/refresh? It seems that the 'default' behavior for vue is the user aren't meant to do a page reload/refresh.. or am I missing something here?
My bad.In my app.vue I have the code below which was somehow the culprit that keeps on redirecting me to login on page reload/refresh. Removing the code below fixed my problem.
mounted() {
if(!this.authenticated) {
this.$router.replace({ name: "login" })
}
},
methods: {
setAuthenticated (status) {
this.authenticated = status
},
logout () {
this.authenticated = false
}
}
I guess this is one of the problem when I tried to follow several vue nodejs authentication tutorial at once lol
Related
I'm a beginner in Vue, and I implemented Auth0 to my Web App using Vue3.
My issue: after logging in, my API call to retrieve data get an unauthorized error 403. If I reload the page, everything is working fine.
What should I do to avoid reloading the page to get authenticated directly?
Here are my scripts:
Main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import './index.css'
import dayjs from 'dayjs'
import Datepicker from 'vue3-date-time-picker'
import 'vue3-date-time-picker/dist/main.css'
import { setupAuth } from './auth/index.js'
import authConfig from './auth/config.js'
function callbackRedirect(appState) {
router.push(appState && appState.targetUrl ? appState.targetUrl : '/' );
}
setupAuth(authConfig, callbackRedirect).then((auth) => {
let app = createApp(App).use(router);
app.config.globalProperties.$dayjs = dayjs;
app.component('Datepicker', Datepicker);
app.use(auth).mount('#app');
})
My App.vue script:
<template>
<div v-if="isAuthenticated">
<NavBar />
<router-view/>
</div>
</template>
<script>
import NavBar from './components/NavBar.vue'
export default {
components: { NavBar },
data(){
return {
isAuthenticated: false,
}
},
async mounted(){
await this.getAccessToken()
},
methods: {
async getAccessToken(){
try {
const accessToken = await this.$auth.getTokenSilently()
localStorage.setItem('accessToken', accessToken)
this.isAuthenticated = true
} catch (error) {
console.log('Error occured while trying to retrieve Access Token...', error)
}
},
},
}
</script>
and my Home.vue loading the data:
<template>
<div class="home">
<div class="py-10">
<header>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<h1 class="text-3xl font-bold leading-tight text-gray-900">Monitoring Dashboard</h1>
</div>
</header>
<main>
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<h3 class="m-5 text-lg leading-6 font-medium text-gray-900">Main KPIs</h3>
<div class="md:grid md:grid-cols-3 md:gap-6">
<div v-for="(item, index) in stats" :key="index" class="md:col-span-1">
<div class="bg-white p-5 border-gray-50 rounded-lg shadow-lg mb-5">
<span class="text-sm font-medium text-gray-500 truncate">{{ item.name }}</span>
<p class="mt-1 text-3xl font-bold text-gray-900">{{ parseFloat(item.stat.toFixed(2)) }}</p>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
</template>
<script>
import _ from 'lodash'
import ProductsService from '../services/products.service'
export default {
name: 'Home',
data(){
return{
user: '',
products: '',
stats: '',
}
},
async mounted(){
await this.readProducts()
await this.buildStats()
},
methods: {
async readProducts(){
let temp = null
try {
temp = await ProductsService.readProducts()
this.products = temp.data
} catch (error) {
console.log('Error: cannot retrieve all products...')
}
},
async buildStats(){
//Nb products
const nbProducts = this.products.length
//Nb offers & Uniq NbRetailers
let nbOffers = 0
let retailers = []
for(let product of this.products){
for(let offer of product.offers){
retailers.push(offer.retailer)
nbOffers += 1
}
}
const nbRetailers = _.uniq(retailers).length
this.stats = [
{ name: 'Number of Retailers', stat: nbRetailers },
{ name: 'Number of Products', stat: nbProducts },
{ name: 'Number of Offers', stat: nbOffers },
]
},
},
watch: {
products: function(){
this.buildStats()
}
}
}
</script>
My ./auth/index.js file:
import createAuth0Client from '#auth0/auth0-spa-js'
import { computed, reactive, watchEffect } from 'vue'
let client
const state = reactive({
loading: true,
isAuthenticated: false,
user: {},
popupOpen: false,
error: null,
})
async function loginWithPopup() {
state.popupOpen = true
try {
await client.loginWithPopup(0)
} catch (e) {
console.error(e)
} finally {
state.popupOpen = false
}
state.user = await client.getUser()
state.isAuthenticated = true
}
async function handleRedirectCallback() {
state.loading = true
try {
await client.handleRedirectCallback()
state.user = await client.getUser()
state.isAuthenticated = true
} catch (e) {
state.error = e
} finally {
state.loading = false
}
}
function loginWithRedirect(o) {
return client.loginWithRedirect(o)
}
function getIdTokenClaims(o) {
return client.getIdTokenClaims(o)
}
function getTokenSilently(o) {
return client.getTokenSilently(o)
}
function getTokenWithPopup(o) {
return client.getTokenWithPopup(o)
}
function logout(o) {
return client.logout(o)
}
export const authPlugin = {
isAuthenticated: computed(() => state.isAuthenticated),
loading: computed(() => state.loading),
user: computed(() => state.user),
getIdTokenClaims,
getTokenSilently,
getTokenWithPopup,
handleRedirectCallback,
loginWithRedirect,
loginWithPopup,
logout,
}
export const routeGuard = (to, from, next) => {
const { isAuthenticated, loading, loginWithRedirect } = authPlugin
const verify = () => {
// If the user is authenticated, continue with the route
if (isAuthenticated.value) {
return next()
}
// Otherwise, log in
loginWithRedirect({ appState: { targetUrl: to.fullPath } })
}
// If loading has already finished, check our auth state using `fn()`
if (!loading.value) {
return verify()
}
// Watch for the loading property to change before we check isAuthenticated
watchEffect(() => {
if (loading.value === false) {
return verify()
}
})
}
export const setupAuth = async (options, callbackRedirect) => {
client = await createAuth0Client({
...options,
})
try {
// If the user is returning to the app after authentication
if (
window.location.search.includes('code=') &&
window.location.search.includes('state=')
) {
// handle the redirect and retrieve tokens
const { appState } = await client.handleRedirectCallback()
// Notify subscribers that the redirect callback has happened, passing the appState
// (useful for retrieving any pre-authentication state)
callbackRedirect(appState)
}
} catch (e) {
state.error = e
} finally {
// Initialize our internal authentication state
state.isAuthenticated = await client.isAuthenticated()
state.user = await client.getUser()
state.loading = false
}
return {
install: (app) => {
app.config.globalProperties.$auth = authPlugin
},
}
}
what I want to do is to prevent the user from entering the login page again if he is logged in,
Likewise, if the login process is successful, the login page will be blocked.
If the user is not logged in, he cannot go to pages such as home about. Likewise, if the login is successful, it will be possible to return to the login or register page.
app.vue
created() {
this.$store.dispatch("initAuth")
},
<template>
<div>
<h1>login</h1>
<div>
<input type="email" v-model="user.email">
</div>
<div>
<input type="password" v-model="user.password">
</div>
<div>
<button #click="login">Giriş Yap</button>
</div>
</div>
</template>
<script>
export default {
name: "Login",
data() {
return {
user: {
email: null,
password: null,
},
isUser: false
}
},
methods: {
login() {
this.$store.dispatch("login", {...this.user, isUser: this.isUser})
}
}
}
</script>
router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
Vue.use(VueRouter)
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: () => import('#/views/Home.vue'),
meta: {
requiresAuth: true
},
},
{
path: '/about',
name: 'about',
component: () => import('#/views/About.vue'),
meta: {
requiresAuth: true,
},
},
{
path: '/login',
name: 'login',
component: () => import('#/views/Login.vue'),
},
{
path: '/register',
name: 'register',
component: () => import('#/views/Register.vue'),
},
{
path: '/error-404',
name: 'error-404',
component: () => import('#/views/error/Error404.vue'),
},
{
path: '*',
redirect: 'error-404',
},
],
})
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.isAuthenticated) {
next({name: 'login'})
} else {
next()
}
} else {
next() // make sure to always call next()!
}
});
export default router
import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios";
import router from '../router';
Vue.use(Vuex)
export default new Vuex.Store({
state: {
token: "",
},
mutations: {
setToken(state, token) {
state.token = token
},
clearToken(state) {
state.token = ""
}
},
actions: {
initAuth({commit, dispatch}) {
let token = localStorage.getItem("token")
if (token) {
commit('setToken', token)
} else {
router.push('/login')
commit('clearToken')
//return false;
}
},
login({commit, dispatch, state}, autData) {
return axios.post(
'/api/login', {
email: autData.email,
password: autData.password
})
.then(response => {
commit('setToken', response.data.token)
localStorage.setItem('token', response.data.token)
router.push('/about')
console.log(response)
})
.catch(error => {
console.log(error)
})
},
register({commit, dispatch, state}, autData) {
return axios.post(
'/api/register', {
name: autData.name,
email: autData.email,
password: autData.password,
password_confirmation: autData.password_confirmation
})
.then(response => {
router.push('/about')
commit('setToken', response.data.token)
console.log(response)
})
.catch(error => {
console.log(error.response.data.errors);
})
},
logout({commit}) {
commit('clearToken')
localStorage.removeItem('token')
router.push('/');
},
setTimeoutTimer({dispatch}, expiresIn) {
setTimeout(() => {
dispatch("logout")
}, expiresIn)
}
},
getters: {
isAuthenticated(state) {
return state.token !== ""
}
},
modules: {},
})
add a new meta key requiresNotAuth for login and register routes then change beforeEach content like this
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!store.getters.isAuthenticated) {
next({name: 'login'})
} else {
next()
}
}
else if (to.matched.some(record => record.meta.requiresNotAuth)) {
if (store.getters.isAuthenticated) {
next({name: 'home'})
}
else {
next()
}
}
else {
next() // make sure to always call next()!
}
After login, I set the state (isLogin: false) value to be true.
So, if the RouterLink in the header.vue bind v-if="$store.state.isLogin === false", I want to make the login router is visible.
If $store.state.isLogin === true, I want to make logout button visible on the header.
So, I tried to solve it with v-if and v-else, but it didn't work well.
If I click the logout button UserLogout() defined in the method must be executed, and logout() mutation must be executed.
So, after the logout mutation was executed, the isLogin value of the state was changed to false, and location.reload() was executed. but it still doesn't work.
If I'm doing something wrong, please tell me what's wrong. Or Please let me know if there is any other good way to make the button visible or invisible depending on login status.
<RouterLink
v-if="$store.state.isLogin === false"
to="/Login"
active-class="active"
class="nav-link">
로그인
</RouterLink>
<button
v-else
type="button"
#click="UserLogout"
active-class="active"
class="nav-link btn btn-primary btn-sm">
로그아웃
</button>
</li>
methods: {
UserLogout() {
this.$store.dispatch('loginService/logout')
}
}
import axios from 'axios'
export default {
namespaced: true,
state: {
UserInfoObj: {
id: '',
password: ''
},
isLogin: false,
isLoginError: false
},
getters: {
},
mutations: {
login: (state) => {
console.log(state.UserInfoObj)
axios.post('http://??.???.???.???:????/api/login', state.UserInfoObj)
.then(res => {
if(res.data.code === "E0008") {
console.log(res)
alert("로그인 완료")
state.isLogin = true
state.isLoginError = false
}
})
.catch(() => {
alert("아이디 또는 비밀번호를 정확히 입력해 주세요.")
})
},
logout(state) {
console.log(state.UserInfoObj)
location.reload()
state.isLogin = false
}
},
actions: {
async login({ commit }, payload) {
return await commit('login', payload)
},
logout({ commit }) {
commit('logout')
}
}
}
According to vuex document:
mutations are synchronous transactions
But you have asynchronous transactions in your login mutation. Try to move asynchronous transactions to action. You can read about actions in here.
<ul class="navbar_menu">
<li class="navbar_item">
<RouterLink
v-if="$store.state.isLogin === false"
to="/Login"
active-class="active"
class="nav-link">
로그인
</RouterLink>
<button
v-else
type="button"
#click="UserLogout"
active-class="active"
class="nav-link btn btn-primary btn-sm">
로그아웃
</button>
</li>
<li class="navbar_item">
<RouterLink
v-if="$store.state.isLogin === false"
to="/Join"
active-class="active"
class="nav-link">
회원가입
</RouterLink>
</li>
methods: {
UserLogout() {
this.$store.commit('loginService/logout')
}
}
import axios from 'axios'
export default {
namespaced: true,
state: {
UserInfoObj: {
id: '',
password: ''
},
isLogin: false,
isLoginError: false
},
getters: {
},
mutations: {
logout(state) {
console.log(state.UserInfoObj)
state.isLogin = false
state.UserInfoObj.id = ''
state.UserInfoObj.password = ''
console.log(state.isLogin)
}
},
actions: {
login: (state) => {
console.log(state.UserInfoObj)
axios.post('http://??.???.???.???:????/api/login', state.UserInfoObj)
.then(res => {
if(res.data.code === "E0008") {
console.log(res)
alert("로그인 완료")
state.isLogin = true
state.isLoginError = false
}
})
.catch(() => {
alert("아이디 또는 비밀번호를 정확히 입력해 주세요.")
})
}
}
}
I am having a problem which I can't seem to solve. First some Code:
<template>
<div>
<q-input name="email" v-model="user.email" />
<q-input name="userName" v-model="user.userName" />
</div>
</template>
<script>
export default {
name: 'UserDetail',
props: {
id: String
},
computed: {
user: {
get () {
return this.$store.state.users.user
},
set (value) {
this.$store.dispatch('users/updateUser', this.id, value)
}
}
}
}
</script>
And here the store action:
export function updateUser ({ commit }, id, user) {
if (id !== user.id) {
console.log('Id und User.Id stimmen nicht überein')
} else {
api.put(`/User/${id}`, user).then(response => {
commit('upsertUser', response.data)
}).catch(error => {
console.log(error)
})
}
}
Mutation:
export const upsertUser = (state, user) => {
const idx = state.userList.findIndex(x => x.id === user.id)
if (idx !== -1) {
state.userList[idx] = user
} else {
state.userList.push(user)
}
if (state.user?.id === user.id) {
state.user = user
}
}
Now as far as I can tell this adheres to the vuex recommendet way of doing things like this (https://vuex.vuejs.org/guide/forms.html#two-way-computed-property)
But I always get the Error: do not mutate vuex store state outside mutation handlers
I can not figure out how to do this. Can someone point me in the right direction?
Dispatching Actions: it only allows one input parameter, from this point you can read the state but you cannot modify it
Mutations: it only allows one input parameter, from here you can read and write about the state, but if you want the variables that listen for the changes of the object to "listen for the changes" you have to use
Object.assign or Vue.set when using objects
I did not understand your data, so I leave you a similar solution, I hope it helps you
let users = {
namespaced: true,
state: {
userList: {
'ID43769906': {
id: 'ID43769906',
email: 'manueltemple#gmail.com',
username: 'mtemple'
}
}
},
mutations: {
upsertUser(state, payload) {
if (state.userList.hasOwnProperty(payload.id)) {
Object.assign(state.userList[payload.id], payload)
} else {
Vue.set(state.userList, payload.id, payload)
}
}
},
actions: {
updateUser({ commit }, payload) {
console.log('api put')
commit('upsertUser', payload)
/*
api.put(`/User/${id}`, user).then(response => {
commit('upsertUser', response.data)
}).catch(error => {
console.log(error)
})
*/
}
},
getters: {
getUser: (state) => (id) => {
let result = null
let data = state.userList || {}
Object.keys(data).forEach((key) => {
if (key === id) {
result = data[key]
return false
}
})
return result
}
}
}
const store = new Vuex.Store({
modules: {
users
},
})
//import { mapGetters } from 'vuex'
new Vue({
store,
el: '#q-app',
data: function () {
return {
id: 'ID43769906'
}
},
mounted () {
window._this = this
},
computed: {
...Vuex.mapGetters('users', ['getUser']),
user: {
get () {
return this.getUser(this.id)
// return _this.$store.getters['users/getUser'](this.id)
},
set (value) {
this.$store.dispatch('users/updateUser', value, { root: true })
}
}
}
})
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/#quasar/extras/material-icons/material-icons.css">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/quasar/dist/quasar.min.css">
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/vuex"></script>
<script src="https://cdn.jsdelivr.net/npm/quasar/dist/quasar.umd.min.js"></script>
<div id="q-app">
<div>
<q-input name="email" v-model="user.email" />
<q-input name="userName" v-model="user.username" />
</div>
</div>
https://jsfiddle.net/idkc/Lu21eqv9/46/
I store the log in status of the user in my store.js (using vuex for state management)
When the user is logged in the login status is set to true in store.js
I check if the user is logged in and using v-if i hide the login button . Till he everything works fine
Now for checking purpose i removed the v-if condition on login button
I set up á before enter navigation guard in my !ogin.vue component as below
login.vue
beforeRouteEnter(to, from, next){
next(vm => {
if(vm.$store.getters.g_loginStatus === true){
next('/');
}else{
next();
}
})
}
If the user is logged in and presses the login button he is redirected to the home page
This works fine as the navigation guard is set up.
but the problem arises when i directly type in the login component url (localhost:8080/login) in the search.
The login component gets loaded normally without getting redirected to home page...
Why does this happen¿ Am i doing something wrong
I enen tried another approach using route meta fields following the documentation at route meta fields
But same problem
when i type the direct url to login component in search not getting redirected
import Vue from 'vue'
import Vuex from 'vuex'
import * as firebase from 'firebase'
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
loggedIn: false,
userName: 'Guest',
error: {
is: false,
errorMessage: ''
},
toast: {
is: false,
toastMessage: ''
}
},
getters: {
g_loginStatus: state => {
return state.loggedIn;
},
g_userName: state => {
return state.userName;
},
g_error: state => {
return state.error;
},
g_toast: (state) => {
return state.toast;
}
},
mutations: {
m_logInUser: (state) => {
state.loggedIn = true;
},
m_loggedOut: (state) => {
state.loggedIn = false;
}
},
actions: {
a_logInUser: ({state, dispatch}, user) => {
return new Promise((resolve, reject) => {
firebase.auth().signInWithEmailAndPassword(user.e, user.p).then(
() =>{
resolve(dispatch('a_authStateObserver'));
}, error => {
state.error.is = true;
let errorCode = error.code;
let errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
state.error.errorMessage = 'Wrong password.';
} else {
state.errorMessage = errorMessage;
}
}
);
});
},
a_loggedOut: () => {
firebase.auth().signOut().then(() => {
dispatch('a_authStateObserver');
});
},
a_signUpUser: ({state, dispatch}, user) => {
return new Promise((resolve, reject) => {
firebase.auth().createUserWithEmailAndPassword(user.e, user.p).then(
(u) =>{
let uid = u.uid;
resolve(dispatch('a_authStateObserver'));
}, error => {
state.error.is = true;
let errorCode = error.code;
let errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
state.error.errorMessage = 'Wrong password.';
} else {
state.errorMessage = errorMessage;
}
}
);
});
},
a_authStateObserver: ({commit, state}) => {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
state.userName = user.email;
state.error.is = false;
commit('m_logInUser');
} else {
// User is signed out.
commit('m_loggedOut');
}
});
}
}
});
login.vue
<template>
<div class="container">
<div class="row">
<div class="form_bg center-block">
<form #submit.prevent="loginUser">
<h3 class="text-center">Log in</h3>
<br/>
<div class="form-group">
<input v-model="email" type="email" class="form-control" placeholder="Your Email">
</div>
<div class="form-group">
<input v-model="password" type="password" class="form-control" placeholder="Password">
</div>
<div class="align-center">
<p class="error" v-if="g_error.is">{{ g_error.errorMessage }}</p>
<button type="submit" class="btn btn-success center-block">Log in</button>
</div>
</form>
<br>
<p style="display:inline-block">Don't have an account?</p>
<router-link to="/signup" tag="a" style="display:inline-block">Sign up</router-link>
</div>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default{
data(){
return{
email: '',
password: ''
};
},
methods: {
loginUser(){
this.$store.dispatch('a_logInUser', {e: this.email, p: this.password}).then(() =>{
this.$router.replace('/statuses');
});
}
},
computed: {
...mapGetters([
'g_error'
])
},
beforeRouteEnter(to, from, next){
next(vm => {
console.log(vm.$store.getters.g_loginStatus);
if(vm.$store.getters.g_loginStatus === true){
next('/');
}else{
next();
}
})
}
}
**routs.js**
import Home from './components/Home.vue'
import Users from './components/user/Users.vue'
import Statuses from './components/user/Statuses.vue'
import Post from './components/Post.vue'
import UserStatus from './components/user/UserStatus.vue'
import Signup from './components/auth/Signup.vue'
import Login from './components/auth/Login.vue'
export const routes = [
{path: '/', component: Home, name:'home'},
{path: '/users', component: Users, name:'users'},
{path: '/statuses', component: Statuses, name:'statuses'},
{path: '/current', component: UserStatus, name:'currentUser'},
{path: '/signup', component: Signup, name:'signup'},
{path: '/login', component: Login, name:'login'},
{path: '/post', component: Post}
];