Is there a way to access the history of Vue routers?

I am looking for a way to determine if the Vue router has additional entries in its history that can be navigated back to. This information is crucial for deciding whether or not to execute the exit app function. The app should only navigate back to previous pages as long as it is possible, but once it reaches the final page, it should exit.

Answer №1

Encountering a similar issue, I had to manage both an angularjs and vue.js app running simultaneously. The approach I took was to switch to the angularjs app once the vue.js history stack was empty. Below is the solution I implemented using vuex:

/** store/history.ts */

import { clientRouter } from '@/views'
import { Route } from 'vue-router'
import { ActionTree, GetterTree, Module, MutationTree } from 'vuex'
import { IRootState } from '.'

export interface IHistoryState {
    history: Route[]
}

const historyState: IHistoryState = {
    history: []
}

const getters: GetterTree<IHistoryState, IRootState> = {
    history: state => state.history
}

const mutations: MutationTree<IHistoryState> = {
    pop: state => state.history.pop(),
    push: (state, route: Route) => state.history.push(route)
}

const actions: ActionTree<IHistoryState, IRootState> = {
    back: context => {
        const history = context.state.history
        if (history.length === 1) {
            window.location.href = '/angular.html'
        }
        else {
            clientRouter.back()
        }
    },
    record: (context, route: Route) => {
        const history = context.state.history

        // Reloading same page
        if (history.length && history[history.length - 1].name === route.name) {
            context.commit('pop')
            context.commit('push', route)
            return false
        }
        // Going back
        else if (history.length > 1 && history[history.length - 2].name === route.name) {
            context.commit('pop')
            return false
        }
        else {
            context.commit('push', route)
            return true
        }
    }
}

export default {
    state: historyState,
    getters,
    mutations,
    actions,
    namespaced: true
} as Module<IHistoryState, IRootState>

Utilizing clientRouter due to SSR, but any router can be used. The code is in typescript, but can be converted to vanilla JS upon request. By following this method, navigation should always happen through the designated action here. To keep track of history, I added the following code to the main app component:

/** app.vue */

@Action('history/record') recordHistory: (to: Route) => forward:boolean

@Watch('$route')
function (to: Route) {
    // Push to history
    this.recordHistory(to)

    // Analytics
    analytics.trackPageView()
}

Answer №2

It seems like there is some confusion in your question regarding the term "As long as the app can go back to a previous page" - are you referring to any page in the browser's history or within your application?

If it's the former, you can achieve this by using:

history.back();
app.exitProcess();

This way, the script will only execute exitProcess if the browser cannot go back in its history.

You may also consider checking out document.referrer, although it might be empty or undefined most of the time.

On the other hand, if you meant the latter scenario, I suggest maintaining a history state to track the last 'back' action within your app and when it would lead to exiting the app and navigating to another site.

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

Issue: Unspecified error when trying to access object attribute in Vue (Nuxt)

I am facing an issue with my 'region' object. It appears to be displayed correctly with all its attributes, but when I try to access specific attributes, it shows up as 'undefined'. const region = { "id": 7, "name": ...

How can we pass a function to a child component in Vue 2.0?

I am facing a challenge with passing a function link to the child component in Vue. Although it is functioning correctly, the code appears in HTML format. How can I enhance this? In my Vue instance, I have: app = new Vue({ ... some code data: { ...

What is the best way to add a change event to a textarea that is already applied with a filtered one-way binding?

I have a text area that is already linked with a filter, so it will display the correct information when the page loads. Now, I want to update a model when the text area content changes. However, when I add a model and change event, the initial binding sto ...

Retrieve data from a form on the server side using an Ajax request

I am currently working on submitting form data through an Ajax call. Here is the relevant form code: <form target="_blank" id="addCaseForm" class="form-horizontal col-md-12" action="" method="POST> <div class="form-group"> <labe ...

What steps can I take to guarantee that a select change event occurs following the setting of ngmodel in Angular2?

I am facing an issue with a select element wherein a basic (change) handler is attached along with an ngmodel. Whenever an <option> with a ng value is set, the change handler triggers before the [(ngModel)] reflects the new values. <div> ...

Unable to retrieve information from JSON file utilizing AngularJS version 1.6

I'm having trouble retrieving data from my JSON file using AngularJs 1.6 myApp.controller("homeCtrl", function($scope, $http) { $scope.Data = []; var getJsonData = function() { $http.get('contactlist.json').then(func ...

"Learn the trick to concealing a modal and unveiling a different one with the power of jquery

Whenever I try to open a modal, then click on a div within the modal in order to close it and open another one, I encounter an issue. The problem is that upon closing the first modal and attempting to display the second one, only the background of the seco ...

What is the proper way to enhance properties?

In the process of developing a Vue3 app using Typescript, one of the components is designed to receive data through props. Initially, everything functioned smoothly with the basic setup: props: { when: String, data: Object }, However, I de ...

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...

eliminate empty lines from csv files during the uploading process in Angular

I have implemented a csv-reader directive that allows users to upload a CSV file. However, I have noticed an issue when uploading a file with spaces between words, resulting in blank lines being displayed. Here is an example: var reader = new FileReader ...

Obtain a collection of information from a web API by utilizing jQuery

Click on the following link to access live data from a web API: This is my first attempt at retrieving data from an API, so I may have missed some settings. To test the connection with the API, I included the following code in the HTML page: <div id= ...

Persistent Vue oAuth login amidst Express error issues

I have set up an Express server on localhost:5000 and a Vue app on localhost:8080 with discord-passport oAuth2 login. The issue arises when I log in and try to make a request through my Vue service handler to localhost:5000/api/users. In the browser, it di ...

How to attach a Vue.js component to the root of an application

I've built a modal.vue component like this: <template> <transition name="modal-transition"> <div class="modal-body" v-if="displayed"> <div class="modal-overlay" @click="displayed = false"& ...

Issues arise when implementing two-way data binding between parent and child components

I'm currently exploring the implementation of two-way data binding between parent and child components. In this case, my child component, phoneInput, accepts a phone number, formats it, and then passes it to the parent using two-way data binding. Over ...

Tips for Accessing a New Website Using the Floating Layer Close Button

How can I trigger the opening of a new browser window when a visitor clicks the close "x" on my floating layer ad? The close button is within an HTML link code ("a href"), but simply putting a URL in there does not seem to work. <script language=" ...

JavaScript communication between clients and servers

I am looking to develop two scripts, one for the client-side and one for the server-side. I came across a snippet that allows for asynchronous calling of JavaScript: <html> <head> </head> <body> <script> (function() { ...

Using Array.push to add an object retrieved from a Redis cache in a Node.js application is causing issues and is not functioning as expected

I've encountered a problem with retrieving all keys from my Redis cache, storing them in an array, and sending that array to the user using Express. The issue arises when I receive an empty array as the response with no objects in it. I attempted to u ...

ReactJS form submissions failing to detect empty input values

My goal is to use react to console.log the input value. Below is the code I've created: import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component{ constructor() { super(); this.proce ...

What is the best way to prevent the deletion of a specific value in ChipInput (material-ui-chip-input)?

Incorporating the chip input feature from material-ui-chip-input into my project has been great for entering emails. However, I am faced with a challenge - I need to disable the ability to delete specific values. Specifically, when populating the input f ...

using javascript to retrieve php variables

After creating a webpage, setting up Apache2 on an Ubuntu server to access it over the internet, and installing PHP5 and MySQL, I encountered issues with accessing database information on my page through a .php file. Despite having a file named test.php th ...