Utilizing Vue.js to track and navigate through browsing history using the browser's

I'm currently working on an application using Vue and Laravel. Instead of relying on vue-router, Laravel is managing my routes.

Within my parent component, I am dynamically loading components based on the state of an object in the data.

One of the methods in my parent component looks like this:

  activateListingForm: function() {
    this.listingFormActive = !this.listingFormActive;
  }

There's a button that triggers this method to toggle the value of this.listingFormActive.

Then in the template of the component, I have the following:

  <transition name="slide-fade">
    <create-listing-form v-if="listingFormActive"></create-listing-form>
    <listings-table v-else></listings-table>
  </transition>

An issue I'm encountering is that some users are clicking the back button in their browser expecting the previous component to load. Is there a way to adjust the state based on the back button?

Thank you!

Answer №1

Completing this task is achievable. I and my coworkers encountered a similar situation while working on this specific page.

To make it function,

  • The URL serves as the definitive source for determining the value of listingFormActive
  • The state of listingFormActive must be consistently saved in the URL whenever it changes.
  • The original state of listingFormActive should be retrieved from the URL.

Firstly, monitor listingFormActive. Upon any state change, use the pushState method to store its state as a URL query.

watch: {
    listingFormActive: {
        handler(v) {
            history.pushState({
                listingFormActive: v
            }, null, `${window.location.pathname}?listingFormActive=${v}`);
        }
    }
}

Include some utility methods for accessing URL queries

methods: {
    currentUrlQuery() {
        return window.location.search
            .replace("?", "")
            .split("&")
            .filter(v => v)
            .map(s => {
                s = s.replace("+", "%20");
                s = s.split("=").map(s => decodeURIComponent(s));
                return {
                    name: s[0],
                    value: s[1]
                };
            });
    },
    getListingFormActive() {
        return this.currentUrlQuery().filter(obj => obj.name === 'listingFormActive').value;
    }
}

The initial state of listingFormActive should align with what you have stored in the URL

data() {
    return {
        listingFormActive: this.getListingFormActive() == 'true' ? true : false
    }
},

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

When utilizing ng-repeat and invoking the function in the HTML, the JSON array values fail to transfer to the HTML form

What I am trying to achieve: I am facing issues with getting the desired dynamic form output. The values are not being displayed and the data is not passing from the JavaScript file to the html form. I have even tried using the console, but it doesn' ...

React Href is not functioning as expected in relative paths

Recently, I delved into React apps and managed to create one with a router. Everything was smooth sailing in dev mode until I tried running index.html from the build folder after npm run build. It seems like all the href links are broken. I suspect somethi ...

Incorporate JavaScript values into an HTML form to submit them to PHP

How can I successfully POST the values of 'vkey' and 'gene+varient' when submitting a form in HTML? The values are retrieved using JS code and displayed correctly on the form, but are not being sent upon submission. <form action="ac ...

Create PDF and Excel files using Javascript on the client side

Are there any client-side Javascript frameworks that are comparable to Jasper Report in Java? I need to be able to generate both PDF and Excel files on the client side (browser) without relying on server-side processing. While I've come across Ja ...

When initially compiling Angular 5, an error (TS2339) may occur, but after a successful compilation, everything runs smoothly

In a unique scenario, I wrote code that fetches information from an API server without knowing the structure of the response fields. Once I receive the response, I need to create a form for updating the data and sending it back. To handle unknown ngModel p ...

Incorporate PHP form and display multiple results simultaneously on a webpage with automatic refreshing

I am currently in the process of designing a call management system for a radio station. The layout I have in mind involves having a form displayed in a div on the left side, and the results shown in another div on the right side. There are 6 phone lines a ...

Are multiple instances of ajax being executed within the modal?

Currently, I am working on a feature that requires an Ajax request. To begin with, the process involves opening a modal by clicking a button with the class '.open-email-modal'. Within this modal, there are two input fields to enter registration d ...

In the realm of Typescript Angular, transferring the value of an object's property to another property within the

I'm working with a large TypeScript object and I am hoping to automate certain parts of it to streamline my workflow. myObject = [ { id: 0, price: 100, isBought: false, click: () => this.buyItem(100, 0) } buyItem (it ...

A neutral-toned backdrop that briefly shows up for a quick 7-second interlude during a background-image

Recently I created a website. On this website, there is a feature where 3 images change every 7 seconds for a total of 3 cycles. The code snippet used for this functionality is as follows: var swap; function run(interval, frames) { var int = 1; ...

What are some methods to manage the timing of sending socket connection requests from the client to the backend server?

Currently using vue-socket.io, my frontend initiates a Socket.io connection request to the backend when the app is first being built or whenever the page is refreshed. This poses an issue for me because the page is initially constructed on the landing page ...

Put <options> into <select> upon clicking on <select>

Is there a way to automatically populate a <select> list upon clicking on it? $(document).ready(function(){ $("body").on("click", "select", function(){ ajax(); //function to add more <option> elements to the select }); }); Loo ...

Encoding large files using the Base64 format

Is there a method to encode a file of, say, 2 gigabytes without splitting it into chunks? I am encountering errors when trying to handle files larger than 2GB due to their size being too large for the filesystem. Breaking the file into smaller chunks is ...

Leveraging the power of Ajax and Nodejs to dynamically refresh content on a webpage

I'm currently working on creating a loop to refresh a webpage every 30 seconds, but I'm facing some challenges with making an ajax call using the setInterval function. Below is a snippet of my server-side code: var app = express() app.get(' ...

Can we make this happen? Navigate through slides to important sections, similar to vertical paging

Imagine a website with vertical "slides" that take up a significant portion of the screen. Is there a way to smoothly add vertical paging to the scrolling? For example, when the user scrolls close to a specific point on the page horizontally, the page will ...

Unlocking the Watch Hook in VueJS 3: A Step-by-Step Guide

I'm currently developing a VueJS application where I need to monitor changes in the user's state from the vuex store and take action accordingly. Although the changes are reflected, it seems that the watch hook is not triggering. Below is the co ...

Can a JavaScript or jQuery function be triggered on input change to perform a PHP call to check a database?

Is it possible to implement live form validation without a page reload? I am looking to add a function like the one below: <input onchange="validate();"></input> function validate() { // PHP here to check input value against table value o ...

XMLHttpRequest encounters issues with 'Access-Control-Allow-Origin'

I have developed a JavaScript file that tracks and saves the coordinates of mouse clicks on a web page using an AJAX call. In one website (domain2), I have included the following code in the head section: <script src="http://www.domain1.com/scan/track/ ...

Switch out the arrow icon in the dropdown menu with an SVG graphic

Looking for a way to customize the dropdown caret in a semantic-ui-react component? Here's how it currently appears: <Dropdown className="hello-dropdown" placeholder="Comapany" onChange={this.someFunction} options={som ...

Creating a responsive HTML, CSS, and JavaScript popup: A step-by-step guide

I'm facing a challenge in making my HTML, CSS, and JavaScript popup responsive. Despite looking into various resources, I haven't been able to find a solution that fits my code. However, I am confident that it is achievable to make it responsive! ...