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

Encountering the error message "myFunction variable is not declared" when using Google Closure Compiler

When attempting to compile two JavaScript files that both use a function declared in only one of the files, an "undeclared" error is returned. To solve this issue, I added the function declaration to my externs file like this: var myFunction = function() ...

react-navigation hook for navigating

Currently, I am utilizing the react-navigation hook and instead of repeating the hook in various components, my goal is to pass navigation as a prop. const navigation = useNavigation(); ... <MyButton resetLocation={resetLocation} navigation= ...

Conversion of UTC timestamp to a timestamp in the specified timezone

this.selectedTimezone="Pacific/Kiritimati"; //this value will come from a dropdown menu These records represent the data.body returned by an API call. Iterating through each record in the dataset: { We are creating a new Date object based on the ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

The error callback encountered {"readyState":4,"status":200,"statusText":"success"} while processing

When I make a call to this url, the response is a JSON object when done directly in the browser. However, when I try to do it via ajax using the following code snippet: $.ajax({ url: url, type: "GET", dataType:"jsonp", succ ...

"Unlocking the Power of Social Interaction with Vue.js

I've successfully integrated a Facebook Login module in my project and it's working well. However, I'm facing difficulties when trying to link the response data with an input field. Can someone guide me on how to achieve this? I'm still ...

The tooltip feature for icon buttons within Material UI list items is not functioning properly as anticipated

Just starting out with Material UI and React, I've encountered a strange UI problem that I can't quite figure out. Hopefully someone here can help me identify what I did wrong. My Approach: I have a List in my code where each list item has butto ...

Having trouble getting webpack and babel to start using npm

Greetings, wonderful people of the internet! I am a newcomer to the enchanting world of programming and I am facing a perplexing issue. Although Webpack is trying to guide me towards the solution, I seem to be struggling with fixing it on my own. const pa ...

An error is being encountered when attempting to execute a Laravel SQL query through an ajax call

My database table is named reg_dental_camp and it contains columns such as id, reg_name, reg_email, reg_phone, reg_type, reg_info, created_at, updated_at I am trying to retrieve the data from this table in Laravel and display it using ajax. This is the f ...

What causes the truncation of the backslash in the string "videos1_visualisation.mp4"?

Check out this example of AngularJS code I've created. The factory contains a list of video sources. var videoPlayer=angular.module('videoPlayer',[]) videoPlayer.controller("videoplayer",["$scope","videolist",function($scope,videolist) ...

Issue encountered: Trying to deploy firebase functions and hosting with vue-cli v3 and node.js leads to an error "No npm package found in functions source directory

My plan is to utilize Vue.js for the Frontend and Firebase Functions (Express.js) + Firestore for the Backend. Step 0: I initiated a new project on Google Firebase, then created a new Service Account with Owner's permissions to be used with Admin SDK ...

Implement the npm datetimepicker library in your Laravel 8 project

I'm attempting to utilize a npm-installed library: https://github.com/xdan/datetimepicker In my resources file app.js, I added it alongside jquery like so: require('bootstrap'); window.$ = require('jquery'); window.jQuery = requir ...

Problem with targeting the .prev() and closest() class of a text input box

Could you please review This Demo and advise why I am unable to select the first .fa class before the text box #name ? This is what I have been trying: $(this).prev().closest(".fa").addClass("err"); within this code block <div class="row"> & ...

Switching icon with jQuery upon clicking

I'm just starting to learn jQuery and I'm working on changing the font icon class when clicked to display a drop down. Right now, it changes the icon and drops down the content as expected. However, I'm facing an issue where I want the icon ...

Practical strategy for developing and launching a TypeScript/Node.js application

I'm currently developing a node.js app using Typescript, which requires compilation to JS before running. As someone with a background in java/jvm, I'm hesitant about the deployment process where code is pushed to git, built/compiled on the serve ...

"Every time an Ajax call is successful, the 'else' clause in

When it comes to using Ajax for user login in the system, I encountered an issue where the Ajax success function would always run the else statement even if the server returned a true Boolean value. This meant that even when the login credentials were vali ...

Steps for performing position by position sorting within an array of arrays of numbers using the Lodash library

My task involves sorting an array of strings: ['1.2.3', '1.5.2', '1.23', '1.20.31'] I am looking for a way to sort the array by splitting each string separated by dots, such as 1.2.3 into ['1','2&apo ...

Is it possible to incorporate jQuery into an AngularJS project?

When it comes to testing, AngularJS is a framework that supports test-driven development. However, jQuery does not follow this approach. Is it acceptable to use jQuery within Angular directives or anywhere in AngularJS for manipulating the DOM? This dilemm ...

Having trouble with the error "vue-cli-service ENOENT not found" after updating Vue CLI?

Yesterday, I encountered errors in my Vue project. Initially, I thought it was a node-related issue as my project was not loading properly, which was unusual. Additionally, I kept receiving an audit problem related to my CLI plugin. After updating Node to ...

How to parse JSON in JavaScript/jQuery while preserving the original order

Below is a json object that I have. var json1 = {"00" : "00", "15" : "15", "30" : "30", "45" : "45"}; I am trying to populate a select element using the above json in the following way. var selElem = $('<select>', {'name' : nam ...