Vue Router consistently triggers browser reloads, causing the loss of Vuex state

I encountered an issue that initially appeared simple, but has turned out to be more complex for me:

After setting up a Vue project using vue-cli with Router, VueX, and PWA functionalities, I defined some routes following the documentation recommendations and created state fields in VueX:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import Logout from '@/components/functional/Logout.vue'
import Datapoints from '@/views/Datapoints.vue'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/login',
    name: 'login',
    component: Login,
    meta: {
      requiresGuest: true
    }
  },
  {
    path: '/logout',
    name: 'logout',
    component: Logout
  },
  {
    path: '/project/:id',
    name: 'project',
    component: Datapoints
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.getters.isAuthenticated) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresGuest)) {
    if (store.getters.isAuthenticated) {
      next({
        path: '/',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router

Within my Views / Components, I utilize the push method on the $router instance for programmatic routing, like so:

this.$router.push({ name: 'home', params: { status: project.response.status, message: project.response.data.error }})

, where project is the result of an awaited axios HTTP request.

The Issue at Hand

Every time I programmatically push a new route or use the router-view element, my page reloads (contrary to what I want in a SPA / PWA setup...)

My Vue instance:

new Vue({
    router,
    store,
    vuetify,
    render: h => h(App)
  }).$mount('#app');

I would greatly appreciate any assistance in resolving the problem of page reloading on every route change with the Vue router.

Answer №1

It seems like the behavior of reloading is connected to the way your router's history mode is set up

const router = new VueRouter({
  mode: 'history',
  routes
})

You could experiment by removing the history mode to observe any changes. If you decide to keep it, make sure to refer to the history mode documentation to ensure all configurations are correct. https://router.vuejs.org/guide/essentials/history-mode.html.

I hope this information proves helpful.

Answer №2

If you want to keep your data in the store unchanged even after refreshing the page, consider using vuex-persistedstate.

`import createPersistedState from "vuex-persistedstate

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()]
});

For more information, check out https://www.npmjs.com/package/vuex-persistedstate

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

Develop a feature within a standard plugin that allows users to add, remove, or refresh content easily

I have developed a simple plugin that builds tables: ; (function ($, window, document, undefined) { // Define the plugin name and default options var pluginName = "tableBuilder", defaults = { }; // Plugin constructor func ...

Post your artwork on Facebook's timeline

I am working on a website that allows users to create custom smartphone cases. One feature I want to implement is the ability for users to share their design on Facebook, including the actual design itself. I have the object and the canvas with the 's ...

Tips on creating an inline editable cell in a Tree View

I've been working on a category tree that includes expand and collapse buttons. You can see what I have so far here: Category Tree Now, I'm looking to make each item inline editable. Can someone guide me on how to achieve this? If you want to t ...

The autocomplete feature in Codemirror seems to be failing specifically when writing JavaScript code

I am having trouble implementing the autocomplete feature in my JavaScript code editor using Codemirror. Can someone please help me figure out what I'm doing wrong? Here is the snippet of code : var editor = CodeMirror.fromTextArea(myTextarea, { ...

Encountering an issue with connecting nodejs to mqlight

I have been working with nodejs and mqlight to test out some sample code provided on https://www.npmjs.com/package/mqlight. My current setup consists of nodejs 5.5.0 and npm version 3.3.12. To install mqlight, I used the command npm install mqlight. ...

The chosenValues.filter method hit an unexpected token; a comma was anticipated

I have encountered a syntax error in the following line: queryComponents: prevState.seletedValues.filter((a, i) => (i !== index)); I am attempting to swap out splice with filter. I've attempted modifying brackets, both adding and removing them, b ...

Encountering difficulties when attempting to store files using mongoose in a node express.js program

I encountered an error while attempting to save a document to the MongoDB using Mongoose in my Node Express.js project. Below is the code snippet: exports.storeJob = async (req, res, next) => { const { name, email, password, title, location, descri ...

Encountering an issue while attempting to test geolocation functionality in the web browser

I've been working on integrating the geolocation API into my app and came across a suitable resource at the MDN website. However, when I attempted to test for the existence of the geolocation object in the browser, I encountered this error: Server Err ...

Dividing a sentence by spaces to isolate individual words

Recently, I encountered a challenging question that has me stuck. I am working on creating an HTML text box where the submitted text is processed by a function to check for any links. If a link is detected, it should be wrapped in anchor tags to make it cl ...

Enhance a React component by including additional properties when passing it into another component through props

I have a parent element with a dynamically changing height that I need to pass down to its child elements. To get and set the height of the parent element, I am utilizing a ref. The challenge lies in passing this height value from the parent component to ...

AngularJS: Solving the issue of controllers not exchanging data by utilizing a service

I am working with the following controllers and service: angular.module('myApp', []); angular.module('myApp').factory('ShareService', function() { var information = {}; information.data = ""; information.setD ...

How can I preserve the file extension of an ejs file as .html?

I'm in the process of building an expressjs application using the ejs template engine. However, I'd like to retain the file extension as .html instead of using .ejs. The main reason for this is that I am using Visual Studio for my development wor ...

Determine the byte size of the ImageData Object

Snippet: // Generate a blank canvas let canvas = document.createElement('canvas'); canvas.width = 100; canvas.height = 100; document.body.appendChild(canvas); // Access the drawing context let ctx = canvas.getContext('2d'); // Extrac ...

Exploring the functionality of multiple index pages in angularjs

I am trying to access the localhost:3000/admin which is located in my views. The index.html and admin.html are two separate base files, one for users and the other for the admin dashboard respectively. Here is a snippet from my app.routes.js file: angul ...

Do not engage with the website while animations are running

I'm working on a JavaScript project where I want to create textareas that grow and center in the window when clicked, and shrink back down when not focused. However, I ran into some issues with the .animate() function that are causing bugs. During QA ...

Tracker.gg's API for Valorant

After receiving help with web scraping using tracker.gg's API and puppeteer, I encountered an error message when the season changed {"errors":[{"code":"CollectorResultStatus::InvalidParameters","message":" ...

Setting up the initial 3 parameters in a v-for loop

What is the best way to begin a v-for loop? For instance, we have an array named "array" with the following values: array = [dog, cat, e, f, g]; I am interested in using a v-for loop that will start looping through and only consider the first 3 values. ...

Using Express Router to serve and display static files in the public directory

The code snippet below is found in my index.js file: var express = require('express'); var app = express(); var PORT = 3000; var routes = require('./scripts/routes/routes'); app.set('views', './views'); app ...

`ACCESS DENIED: Unauthorized access attempt detected in Node.js``

When attempting to connect, MySQL is establishing a connection with an unfamiliar IP address. Refer to the code below: .env MYSQL_HOST=domain.example.com MYSQL_USER=**** MYSQL_PASSWORD=**** MYSQL_DB=**** MYSQL_PORT=3306 connection.js const mysql = requir ...

Divide a SINGLE BACKGROUND IMAGE in HTML into two separate links of equal size, one at the top and

As a beginner in HTML, I am trying to find a way to divide a background image into two equal sections without using image mapping. I attempted to split the links by setting the style to 0% and 50% to designate the top and bottom halves, but unfortunately, ...