I am currently working on a small CRM project. Within the login form, I have implemented a component that displays an alert message when the email or password entered is incorrect. Interestingly, even after correcting the information and logging out, the message persists unless the page is manually refreshed.
To address this issue, I attempted to utilize the watch
feature by accessing $route
to clear the state of the message every time the route changes.
Within Alert.vue:
<template>
<div :class="'alert ' + alert.type">{{alert.message}}</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: mapState({
alert: state => state.alert
}),
methods: mapActions({
clearAlert: 'alert/clear'
}),
watch: {
$route (to, from){
console.log('inside $route');
this.clearAlert();
}
}
};
</script>
Within main.js:
import Vue from 'vue';
import { store } from './_store';
import { router } from './_helpers';
import App from './components/App';
import './css/main.css';
new Vue({
el: '#app',
router,
store,
render: h => h(App)
});
Within router.js:
import Vue from 'vue';
import Router from 'vue-router';
import Dashboard from '../components/Dashboard.vue';
import LoginPage from '../components/LoginPage.vue';
import UserPage from '../components/UserPage.vue';
Vue.use(Router);
export const router = new Router({
mode: 'history',
routes: [
{ path: '/app', component: Dashboard },
{ path: '/login', component: LoginPage },
{ path: '/app/user-info', component: UserPage },
{ path: '*', redirect: '/app' }
]
});
router.beforeEach((to, from, next) => {
const allowedPages = ['/login'];
const authRequired = !allowedPages.includes(to.path);
const loggedIn = localStorage.getItem('user');
if (authRequired && !loggedIn) {
return next('/login');
}
next();
})
I followed the methods outlined in the documentation at https://router.vuejs.org/guide/essentials/dynamic-matching.html, but for some reason, the $route
is not being recognized and I am unable to access it.
It is worth mentioning that in my main.js file, I import the router.js file which in turn imports Router from 'vue-router' and instantiates it, making $route
accessible from all components. Can anyone provide insight into why this may be happening?
Link to my project: repo