Vue router beforeRouteEnter - when the page is refreshed, the button label vanishes

<script>
export default {
  name: 'TEST',
   data() {
    return {
      prevRoute: ''
    }
  },
  methods: {
    goBack() {
      return this.$router.go(-1);
    },
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.prevRoute = from.name
      console.log(from.name)
    })
  },
}
</script>
<template> 
 <div>
  <button @click="goBack" class="back">{{ prevRoute }}</button>
 </div>
</template>

Is there a way to prevent the disappearance of the text "{{ prevRoute }}" in the button after refreshing the page when using Vue router's beforeRouteEnter function? Are there alternative methods to display text in the button for the previous page?

Answer №1

It's not feasible to retain the previous route upon refresh, as the from route will always be empty in such cases. One possible solution is to store the name of the route you are coming from (from.name) in your localStorage, and only set this item if from.name actually exists.

beforeRouteEnter(to, from, next) {
    if (from.name) localStorage.setItem('from_route', from.name)
    next()
},        

In the mounted hook, retrieve the stored value for prevRoute from localStorage.

mounted () {
    this.from_route = localStorage.getItem('from_route')
},

Note that this approach may encounter issues if someone shares a link with you, and you do not have any previous page history.

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 is the best way to adjust the priority of elements using JavaScript in an ASP.NET MVC application?

As part of my application, I need to create a function that allows for the changing of deputy priorities for each consultant. Here is what I have implemented so far: View: @model ML.Domain.DAL.DB_CONSULTANTS .... <table> <tr> < ...

What is the best way to keep the calendar of a Datepicker always visible while still being able to select a date easily?

When I write my code, the calendar only appears when I press the TextBox. I attempted to place the datepicker in a <div>, but then I was unable to retrieve the selected date. @model Plotting.Models.CalendarModel @using (Html.BeginForm("Calendar", "H ...

Error Alert: LocalStorage is undefined in this context - NextJS

Having trouble retrieving access and refresh tokens from local storage. Each attempt results in a 500: Internal Server Error, with an error indicating LocalStorage is undefined. Research suggests that LocalStorage may not be compatible with rendering with ...

Using data variables as arguments in the style section of Vue2

Suppose we have a data variable and I want to utilize this data variable for styling purposes. data() { return{ selected:{ index: 2 } } } <style> .parent-table >>> .table-row:nth-child(/* here I intend to use ...

methods for retrieving nested JSON data from an API endpoint

My data has been exported in JSON format { "count":79, "stories":{ "23658975":{ "title":"NOMINATIVO", "description":"BUSDRAGHI PIERGIORGIO", "updated_at":"2013-06-16T18:55:56+02:00", "created_at":"2013-06-16T18:39:06+02:00", "du ...

Retrieve Data from MySQL Database Using ExpressJS Pool Connection

I am relatively new to ExpressJS. I am encountering an issue where console.log is working fine and I can see the data in the terminal when I make a call. However, the data is not being returned as a response. Even after using console.log and return stateme ...

Easily adding multiple field data with the same field name into a database can be achieved using Mongoose and Node.js (specifically Express

I am new to using nodejs and exploring the creation of a project focused on generating invoices. My goal is to store product information in mongodb utilizing mongoose and express, but I'm unsure of how to proceed. Below is a snippet of my HTML code.. ...

What could be the reason behind the child component updating without triggering a re-render in Reactjs?

I am encountering an issue with my main component and child chart component. Even though the main component updates the state of the child chart component upon connecting to a websocket, the chart does not redraw as expected. Interestingly, when I click on ...

Error: The module could not be located due to the inability to resolve the path to './router'. This issue is specifically related to Vue router

Looking at the search.js file: import {createRouter, createWebHistory} from "vue-router"; import SearchIndex from './components/omdb/SearchIndex.vue' const routes = [ { path: '/', name: 'welcome&apos ...

How can the jQuery click() method be utilized?

Currently working on a web scraping project, I have managed to gather some valuable data. However, I am now faced with the challenge of looping through multiple pages. Update: Using nodeJS for this project Knowing that there are 10 pages in total, I atte ...

Clicking on Fixed Positioning triggers a reset

When I activate the sidebar by clicking the menu button, it remains fixed in position until the first scroll. However, if I interact with the sidebar by clicking on it, the button resets and goes back to the top of the page. This issue seems to only occur ...

Using React JS to automatically execute an event based on a specific state value

Is there a way to initiate an action from a main component when the child component's state reaches a specific value? Let's consider a scenario where I have a Parent component and a Child component, with the parent's state containing active ...

Enable the duplication of strings within an array

Below is the HTML code snippet I am working with: <div class="col-sm-8"> <div class="row col-sm-12 pull-right paddingDiv"> <div class="col-sm-12"> <div class="marginBottom pull-right"> <bu ...

Bringing in the jqGrid library with Meteor using NPM

I am currently working on a project using Meteor and I want to incorporate the free-jqgrid library. However, I am unsure of the correct way to import this library... I have tried: import 'free-jqgrid'; import jqGrid from 'free-jqgrid&apo ...

Having trouble loading items in a <select> tag with Jquery?

Dealing with a seemingly simple issue, I am struggling to figure out how to load items into a select using jQuery. Working with the Materialize theme available at: The code snippet in question: <div class="input-field col s12"> <s ...

1. Catalog of dual JSON inquiries2. Compilation of

I am struggling to understand the right way to proceed. When I run this query, I receive a JSON response containing file names: $.getJSON("http://api.server.com/my/?callback=?", function(data){ var results = []; $.each(data['resul ...

Share a status on Facebook with an earlier date

How to Modify Facebook Post Date using Graph API facebook facebook-graph-api I am able to publish on my wall using the Graph API. By utilizing FB nod and graph, I now need to post on Facebook with a date from the past Afterwards, I can adjust the date man ...

Concealing the rear navigation button within the material carousel

I have a material css carousel, and I am trying to hide the back button on the first slide. I attempted to use the code below from a previous post The following code snippet prevents the user from looping through the carousel indefinitely. Stop looping i ...

Angular ngView not displaying content on the page

To load a ngView page by clicking on a link, the html file does not appear as expected. Running the application directly without using localhost might be causing the issue. I simply opened index.html with Chrome browser, so it's possible that there i ...

What is the most effective way for AngularJS controllers to communicate with one another?

As I develop a controller, it must interact with another controller. However, I'm uncertain if this is achievable? HTML: <div data-ng-app="TestApp"> <div data-ng-controller="menuCtrl"> <ul> <li> <a data-ng-clic ...