Observing modifications in the $route object - Vue Router

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

Answer №1

Your setup for the $route watcher is on point, and you can verify that your component has access to $route by logging it in the mounted() hook.

The issue lies in the fact that the Alert.vue component, where the watcher is placed, gets destroyed when navigating away from the page. This prevents the watcher from being triggered. To fix this, consider moving the $route watcher to a component that remains alive at all times, such as App.vue, and you should see it functioning correctly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What will occur if I use an XMLHttpRequest to request a file that is currently being downloaded?

My goal is to enhance links in a progressive manner using the PJAX style. My plan was to layer this on top of some regular prefetch <link>s: <link rel="prefetch" href="next.html"/> If the browser has already downloaded next.html, then the PJA ...

When I try to set a property for the drawer to dispatch the toggleDrawer action in Vue, the page fails to

One of my Vue components, Sidebar, includes a navigation drawer created with Vuetify. The drawer's state is managed using v-model, with the state itself stored in Vuex to allow other components to modify it. However, when I define a setter for the com ...

Using Node.js to update information within Firebase

Here's a problem I'm facing: I have a cron job running in Node.js that sends data to a Firebase database every minute. The issue is, even when there are no changes, the database still receives information. Take a look at my code snippet below: l ...

Experience a different div content by simply hovering over it

Is there a way to implement a hover effect that displays an image over the entire display-div? For example, when hovering over item1, the image should cover the display-div, and when hovering over another item, the image within the display-div should chang ...

Navigating the world of streams in JavaScript

Is there a way to manipulate arrays in JavaScript in a similar manner to Java Streams? For example: arr.map().map().map() Currently, this would only perform a single iteration. How can I accomplish this without using a library? ...

invoking a PHP function within a JavaScript script

In my collection of essential functions, there is one that I am particularly interested in: //the functions file //........ function user_exists($username){ $username = sanitize($username); $query = mysql_query("SELECT COUNT('user_id') F ...

Fade In/Out Scroll Effect

As the user scrolls down the page, I have a slider that smoothly slides from right to left. What I'm trying to achieve is for the slider to fade out when the last slide is no longer in view during downward scrolling, and fade back in as the last slid ...

Trouble with React Material Select Options Failing to Populate

After iterating and producing MenuItems, I am able to see the items when I console.log, but in the UI, the dropdown appears empty. I'm puzzled as to why the Select's are not being populated. Any thoughts on this issue? Below is the supplied code ...

Angular 13 does not currently have support for the experimental syntax 'importMeta' activated

Since upgrading to angular 13, I've encountered an issue while attempting to create a worker in the following manner: new Worker(new URL('../path/to/worker', import.meta.url), {type: 'module'}) This code works as expected with "ng ...

Vue template is not being rendered when served through Django

I am currently working on a Django application where Vue is used as the frontend to render templates. In my Django view code, I have the following components: # thing/views.py def index(request): template = loader.get_template('thing/index.html&a ...

What is the best way to apply a CSS class to elements in a Vue.js template when using a v-for

Is there a way to dynamically name my td class after the step in this particular scenario? <td v-for="step in item.steps" :class="step.name"> {{ step.name }} </td> Currently, the class is being assigned as "item.steps.name" instead of taking ...

Develop a custom function in Typescript that resolves and returns the values from multiple other functions

Is there a simple solution to my dilemma? I'm attempting to develop a function that gathers the outcomes of multiple functions into an array. TypeScript seems to be raising objections. How can I correctly modify this function? const func = (x:number, ...

Issues with the Diagonal HTML Map functionality

I'm seeking assistance to implement a unique Google Maps Map on my webpage. I have a particular vision in mind - a diagonal map (as pictured below). My initial approach was to create a div, skew it with CSS, place the map inside, and then skew the ma ...

Utilize DataTables with a custom search form for enhanced data filtering

I rely on DataTables for its advanced functionality in creating tables with paging capabilities. When submitting data through a standard jQuery Ajax request using my own form, the returned data is formatted and then passed to the DataTables function to en ...

When troubleshooting the "Uncaught reference error: require is not defined," the browserify command encountered the error message "Error: Cannot find module."

I am encountering a similar issue to @RachelD in the thread discussing the Uncaught reference error. When I execute the 'browserify' command following the instructions provided here, and using my directory as a reference, like so... myname@compn ...

how to execute a javascript function in an ionic controller from the template

My journey in creating my first Ionic app has been smooth so far. I am not well-versed in UI design, so I may not be implementing the best practices, but I am making progress nonetheless... Within a template, I have encountered the following code snippet ...

Downloading a zip file using PHP works successfully when initiated directly, but encounters errors when attempted through a web application

I have been working on a PHP script that generates a zip file and allows it to be downloaded from the browser. The download function in the code snippet below: download.php // ensure client receives download if (headers_sent()) { echo 'HTTP head ...

Sorting data by percentages in AngularJS

I am currently facing an issue with sorting percentages in a table column. Despite using methods like parseFloat and other AngularJS (1.5.0) sorting techniques, the percentages are not being sorted as expected. [ {percentage: 8.82} {percentage: 0. ...

Switching from Ldapsearch to ldapjs transformation

I've been experimenting with converting a ldapsearch query from ldapsearch to an ldapjs script: ldapsearch -H ldap://ldap.berkeley.edu -x -b 'ou=people,dc=berkeley,dc=edu' objectclass=* Here is the ldapjs script I have been working on: va ...

What could be causing this error to occur when running my React app and clicking the submit button on the form?

CodeBlock.js import React from "react"; import { useState } from "react"; import axios from 'axios' const CodeBlock=()=>{ const [formData, setFormData]=useState({name:'', password:''}); const hand ...