File tree Expand file tree Collapse file tree 3 files changed +27
-2
lines changed
Expand file tree Collapse file tree 3 files changed +27
-2
lines changed Original file line number Diff line number Diff line change 33 <router-link to =" /" >
44 Home
55 </router-link >
6- <router-link to =" /dashboard" >
6+ <router-link v-if = " loggedIn " to =" /dashboard" >
77 Dashboard
88 </router-link >
99 <router-link v-if =" !loggedIn" to =" /login" class =" button" >
1010 Login
1111 </router-link >
12+ <button v-else type =" button" class =" logoutButton" @click =" logout" >
13+ Logout
14+ </button >
1215 </div >
1316</template >
1417
@@ -17,6 +20,11 @@ import { authComputed } from '../vuex/helpers.js'
1720export default {
1821 computed: {
1922 ... authComputed
23+ },
24+ methods: {
25+ logout () {
26+ this .$store .dispatch (' logout' )
27+ }
2028 }
2129}
2230 </script >
Original file line number Diff line number Diff line change @@ -19,7 +19,8 @@ const router = new Router({
1919 {
2020 path : '/dashboard' ,
2121 name : 'dashboard' ,
22- component : Dashboard
22+ component : Dashboard ,
23+ meta : { requiresAuth : true }
2324 } ,
2425 {
2526 path : '/register' ,
@@ -34,4 +35,13 @@ const router = new Router({
3435 ]
3536} )
3637
38+ router . beforeEach ( ( to , from , next ) => {
39+ const loggedIn = localStorage . getItem ( 'user' )
40+
41+ if ( to . matched . some ( record => record . meta . requiresAuth ) && ! loggedIn ) {
42+ next ( '/' )
43+ }
44+ next ( )
45+ } )
46+
3747export default router
Original file line number Diff line number Diff line change @@ -15,6 +15,10 @@ export default new Vuex.Store({
1515 axios . defaults . headers . common [ 'Authorization' ] = `Bearer ${
1616 userData . token
1717 } `
18+ } ,
19+ CLEAR_USER_DATA ( ) {
20+ localStorage . removeItem ( 'user' )
21+ location . reload ( )
1822 }
1923 } ,
2024 actions : {
@@ -31,6 +35,9 @@ export default new Vuex.Store({
3135 . then ( ( { data } ) => {
3236 commit ( 'SET_USER_DATA' , data )
3337 } )
38+ } ,
39+ logout ( { commit } ) {
40+ commit ( 'CLEAR_USER_DATA' )
3441 }
3542 } ,
3643 getters : {
You can’t perform that action at this time.
0 commit comments