Creating custom back button functionality in Vue.js to mimic an app-like experience with routing

As I work on my cordova Vue app, I often encounter deeper links like this:

/profile/:id/:contact_type/contacts:contact_id

Usually, you would start on /profile/:id and then navigate to

/profile/:id/:contact_type/contacts:contact_id
by clicking a link.

The standard router.go(-1) function works well if you were on the profile page initially. However, if you come from a different page, such as /settings/:id due to a notification or other trigger, the back button should function more like an Up button. Pressing back on

/profile/:id/:contact_type/contacts:contact_id
should take you to /profile/:id, not /settings/:id.

How can I achieve this? I've attempted various methods like splitting the current route by /, removing the last segment, then rejoining and pushing to that route. However, this approach doesn't work well with parameters, especially when there are multiple ones.

const path = router.currentRoute.path
const URLSplit = path.split('/')
URLSplit.length = URLSplit.length - 1
const newTarget = URLSplit.join('/')
if (newTarget) {
  router.push(newTarget)
} else {
  router.push('/home')
}

I also explored using child routes, but that requires a router-view in each page, which isn't ideal for my needs.

I have already intercepted the back button operation, but I am curious if there is a way to configure Vue to handle this type of back navigation automatically, or if there's a specific setup needed in the router, or perhaps a function that can determine the current route and navigate up to it?

Answer №1

It seems that implementing a back button within the app would go against the original purpose of navigating between historical/visited pages, rather than simply moving up one level in the routes.

Instead of trying to alter the browser's default behavior for the back button, consider adding a dedicated in-app back button, similar to what Google apps have. This can be achieved by listening to the popstate event of the Window interface, which is triggered when the active history entry changes. Alternatively, you can explore a workaround using Global Before (navigation) Guards.

An in-app back button, or technically an "up" button, can utilize In-Component Guards.

For instance, within the routes configuration:

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/profile/:id',
      name: 'profile',
      component: Profile,

      children: [{
        path: ':contact_type/contacts:contact_id',
        name: 'contact',
        component: Contact
      }]
    }
  ]
})

You can define the route navigation guards directly inside the corresponding route component (e.g., Contacts.vue):

<template>
  <div>
    <router-link :to="{ name: 'profile' }">&lt;- back to profile</router-link>

    Some contact information.
  </div>
</template>

<script>
  export default {
    beforeRouteLeave(to, from, next) {
      if (from.name === 'contact' && to.name !== 'profile') {
        next({
          name: 'profile',
          params: {
            id: from.params.id
          }
        });
      }
      else {
        next();
      }
    }
  }
</script>

While not necessarily the optimal solution, this approach should suffice.

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

Can D3 transform regions into drinking establishments?

I can create a graph using D3 areas, as shown in this example: https://i.sstatic.net/jaxJb.png Now, I want to add an animation to this graph. When the webpage loads, the initial figure will be displayed. Then, each area will morph into a bar chart. Addit ...

What are the steps to customizing a package on atmospherejs.com within meteor.js?

When working with atmosphere in meteor.js, installing a package is typically as simple as using a single command. However, if there is a need to make changes to a specific package for customization purposes, the process becomes a bit more complex. For ex ...

Incorporating Products from an Iframe into the Cart on Woocommerce

I recently set up a store using WooCommerce, and I have a unique situation where my customizable products are displayed within an iframe. The "add to cart" button is also contained in this iframe. Whenever I click on the Add to Cart button, I receive a mes ...

Ways to incorporate a php file based on the user's selection

I have numerous div elements, possibly a dozen or two, such as... <div class="mydivs" id="firstdiv"></div> <div class="mydivs" id="seconddiv"></div> <div class="mydivs" id="thirddiv"></div> <div class="mydivs" id="fo ...

Error: The data from the intermediate value cannot be parsed using the parseFromString() method and replaced with another value,

I'm working on a project where I need to display parsed HTML content within an element. However, before displaying it, I need to make some changes to the HTML using the `replace` method. But unfortunately, I encountered a TypeError: (intermediate valu ...

Having trouble with the $.get function in AJAX with Rails 4? It seems

After working with Rails for a few years, I decided to dip my toes into the world of AJAX. With a Rails 4 app in hand, I'm currently testing out some functions. My end goal is to reload a partial on the edit page located at app/views/stories/edit.html ...

Error message: Encountered JavaScript heap out-of-memory error during Azure DevOps React Container Production Build

I am facing challenges in building a React production Docker container with Azure DevOps pipelines. Despite upgrading my build environment and code, the pipeline failed to run successfully. After conducting some research, I attempted to add the "--node-fla ...

"Encountering a Javascript issue while trying to apply a CSS class to a

Encountering issues in Safari desktop / mobile and Internet Explorer. The error message states: In Safari: TypeError: Attempted to assign to readonly property. IE Edge: Assignment to read-only properties is not allowed in strict mode The problem arises ...

Creating dynamic height based on width using JavaScript

I'm trying to make a rectangle responsive based on the width of the window. This is my current logic: aspectRatio = 16 / 9 win = { width: window.innerWidth, height: window.innerHeight, } get browser() { const width = this.win.width - 250 ...

A fatal error has occurred in Node as it is unable to set headers after

Just getting started with nodeJs and I'm attempting to read a file from the system. It seems like I can view the file content in the console, but for some reason it's not displaying in the browser. Any ideas what I might be overlooking? var myD ...

Initiate an AJAX call with various data formats included

I am currently developing an application that allows users to input values through an interface and send AJAX requests (similar to a REST API). My question pertains to sending data of multiple types in a single request. For example, here is a scenario: F ...

Transforming the color of a globe from black to white with gio js

After searching for a solution to change the color of a Three.js globe, I came across a link that didn't work as expected: Change the color of a Three.js globe. My goal is to change the globe color from black to white using . I attempted to use the f ...

You cannot access the property 'subscribe' on a void type in Angular 2

fetchNews(newsCategory : any){ this.storage.get("USER_INFO").then(result =>{ this.storage.get("sessionkey").then(tempSessionKey =>{ this.email = JSON.parse(result).email; this.newSessionKey = tempSessionKey; this.authKey =JSON.stringify("Basic ...

Proceed the flow of event propagation using the react-aria button element

In the react-aria library, event bubbling for buttons is disabled. I am facing an issue where my button, which is nested inside a div that acts as a file uploader, does not trigger the file explorer when clicked due to event bubbling being disabled. How ...

Extract website addresses from a text and store them in an array

I am currently attempting to extract URLs from a string and store them in an array. I have implemented a node module to assist with this task. const getUrls = require("get-urls") url = getUrls(message.content) However, the current implementation fails to ...

Check the status of the audio source URL using JavaScript

I am currently live streaming audio to my player using the Soundcloud API. <audio></aidio> <source src="soundcloud-track-url"></source> Within my code, I have added an onerror eventListener for both the <audio> and <sourc ...

I am unable to incorporate added height into the component

In my current project using react.js, material-ui, and sass, I had the task of creating a ChatBit component. After writing it, here is the code: customComponent.js file. // @flow import * as React from 'react'; import { useState } f ...

What steps should I take to set up nuxt 3 in such a way that it functions properly when I attempt to directly access a static page created through the command

Everything is functioning properly in my project when I execute npm run generate followed by npx serve .output/public. However, if I open the index.html file located in .output/public directory directly through my file system, only the initial display appe ...

The Tab style in Mobile Angular UI does not get applied correctly when nested within an ng-repear

While working on a tabbed control with mobile-angular-ui (), I encountered an issue when trying to generate the tabs dynamically. Initially, everything looked good with the following code: <ul class="nav nav-tabs" ui-state='activeTab' ui-def ...

I am struggling to comprehend the code for a PHP form that triggers a JS OnUpdate event, which then uses AJAX to retrieve data from MySQLi

I want to give a special thanks to Alon Alexander for providing the JS and AJAX code, even though I don't fully comprehend it. I am more comfortable using PHP/JS without jQuery, but I am struggling to make it function as intended. My current issue in ...