Skip to content

Commit c7337e1

Browse files
committed
User Logout code
1 parent 8a35cad commit c7337e1

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

src/components/AppNav.vue

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,15 @@
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'
1720
export default {
1821
computed: {
1922
...authComputed
23+
},
24+
methods: {
25+
logout () {
26+
this.$store.dispatch('logout')
27+
}
2028
}
2129
}
2230
</script>

src/router.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff 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+
3747
export default router

src/vuex/store.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff 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: {

0 commit comments

Comments
 (0)