Issue with loading component in Vue.js app due to browser navigation issue

Currently working on a Vue.js single-page application, I am facing an issue with proper navigation when using the browser's back/forward buttons.

Upon attempting to navigate with these buttons, no new pages are created. The URL changes but components fail to load, unless navigating back to the base URL where the component is initially loaded.

The templates seem to not load at all, despite having ESlint that shows no errors.

Below is my index.js for the router setup:

Vue.use(Router);

export default new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'search',
      component: Search,
    },
    {
      path: '/results?terms=:terms',
      name: 'results',
      component: Results,
    },
    {
      path: '/review?id=:id',
      name: 'review',
      component: Review,
    },
  ],
});

To change pages, I am currently using this method:

this.$router.push({ name: 'results', params: { terms: this.terms } });

Being fairly new to Vue, I suspect it might be a simple mistake on my end. However, I have already spent quite some time troubleshooting without success. Any assistance would be greatly appreciated. Thank you.

Answer №1

The problem at hand is that passing route parameters as query string parameters is not the correct approach. Route parameters should only be used within the URL path.

Interestingly, while the router can manage programmatic navigation just fine, it struggles with direct URL loading.

If you still prefer using query strings instead of path parameters, I recommend making the following adjustments...

  1. Declare props for your components, like so:

    export default {
      name: 'Results',
      props: ['terms'],
      // etc
    
  2. Pass the query string variables as props in your route definition

    {
      name: 'results',
      path: '/results',
      component: Results,
      props: route => ({ terms: route.query.terms })
    }
    
  3. Use query instead of params during programmatic navigation

    this.$router.push({ name: 'results', query: { terms: this.terms } })
    

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 implement a table using JavaScript?

I am struggling to add a table to my HTML document dynamically using JavaScript. Despite trying various methods like appendChild and insertBefore, I have not been successful. Below is the snippet of my JavaScript code: //JavaScript code here... Here is ...

Is there a way to retrieve a particular component from an HTML template in VueJS?

After successfully integrating VueJS into my Django project using webpack loader, I have encountered some difficulties due to being new to Vue and struggling with understanding its structure. Here is the current template: django_template.html: where the ...

What sets apart .addEventListener and .on() when it comes to including an event in Bootstrap 5?

I'm currently attempting to attach a listener to my modal in order to implement a certain behavior each time the modal is opened. As per the guidance from Bootstrap 5 documentation, you can achieve this by using: https://getbootstrap.com/docs/5.2/com ...

Is it possible to obtain the X-Y coordinates of the ray collision location in relation to the targeted face?

I have been working on determining the ray collision coordinate in relation to the targeted face... The following is my code snippet: var fMouseX = (iX / oCanvas.width) * 2 - 1; var fMouseY = -(iY / oCanvas.height) * 2 + 1; //Utilizing OrthographicCamer ...

Requesting a large JSON file using AngularJS

I have a challenge where I need to present detailed data from a database to the user. The information is stored in a JSON file that is quite large, approximately 15MB in size. To tackle this issue, I created a service and utilized the promise api to succes ...

Is it possible to utilize a variable as a column name in MySQL when working with Express?

At the moment, I am encountering an issue where the table name is surrounded by quotation marks as it is a string. This causes the server to crash. const update = 'the name of my column'; const UpdateQuery = `UPDATE scores SET ${mysql.escap ...

Guide on incorporating pinching gestures for zooming in and out using JavaScript

I have been working on implementing pinch zoom in and out functionality in JavaScript. I have made progress by figuring out how to detect these gestures using touch events. var dist1=0; function start(ev) { if (ev.targetTouches.length == 2) {//checkin ...

What is the most efficient method in React for displaying an array as a table and wrapping every set of five elements with a <tr> tag?

Currently, I am working on rendering a table in React from an array of objects. My approach involves mapping the array to create table elements as shown below: var objects = response.data; var arrayOfTableElements = [] ...

Tips for updating an input field using JavaScript

Here is a simple code snippet that I have written. <script language='javascript"> function check() {} </script> <div id="a">input type="text" name="b"> <input type="button" onClic ...

Issue with FullCalendar-vue and Typescript: the property 'getApi' is not recognized

Struggling to integrate FullCalendar-vue with Typescript, I encountered a problem when trying to access its API. This is how my calendar is set up: <FullCalendar ref="fullCalendar" :options="calendarOptions" style="width: 100%& ...

When attempting to retrieve the value of a textbox using JavaScript, the outcome may sometimes be null

Here is the code: <input name="xy" size="2" type="text" /> The above input tag is supposed to create a textbox that looks and acts like one. When using JavaScript as shown below: alert(document.getElementById("xy")); the alert returns null. De ...

Slow rendering occurs with unthrottled range input, even with proper throttling applied

I'm currently seeking some general guidelines because I'm unsure where to turn for help at the moment. The issue I am facing involves an uncontrolled input[type=range] slider that performs very slowly when there are numerous steps (works fine wi ...

Extract the file name from a URL using Vue

I have a URL for a file that I need to display to users after slicing. Initially, I successfully sliced the URL using substring, but now I face an issue with varying numbers in the string to be sliced. For example, if the URL is /media/users/3/sample.doc ...

How can I detect a click event on an SVG element using JavaScript or jQuery?

Currently, I am developing a web application that utilizes SVG. However, I have encountered an issue: I am struggling to add a click event to each element within the SVG using jQuery. The problem arises when attempting to trigger the event; it seems like t ...

Tips for accessing a variable located in a different directory

I'm facing some confusion regarding creating a global variable that can be accessed in another file. Currently, I have a chat and login folder setup. Within the login folder, there are three possible users to choose from. When a user clicks on one of ...

Troubles arise with JavaScript CSS override functionality when specifically targeting Android API 19 devices

Below is the code I am currently implementing: view.loadUrl("javascript:var con = document.getElementsByTagName('img'); for (var i = 0; i < con.length; ++i)con[i].style.maxWidth='100%'; "); When targeting API 18, this code function ...

The Mysterious Behavior of ThreeJS Object3D.lookAt Animation

I am facing an issue while trying to animate the lookAt method of an Object3D to face a target Vector3. I am using a Tween function that changes floating points based on the scalarMultiplyVal (ranging from 0.0 to 1.0). However, no matter what approach I ta ...

Learn how to trigger an HTTP exception after a failed command in a saga with NestJS CQRS

Currently utilizing the NestJS CQRS pattern to handle interactions between User and UserProfile entities within my system. The setup consists of an API Gateway NestJS server along with dedicated NestJS servers for each microservice (User, UserProfile, etc. ...

Timing of Bindings in AngularJS

In my setup, I have a controller that calls a service to retrieve a list of categories: $scope.enquiryCategories = CategoryServices.listCategories(); The service then fetches this data from an external API: listCategories: function () { return $http({ ...

Utilizing VUETIFY DataTable: Implementing v-if in table header to conceal specific columns from users

I need to restrict access to the action for non-admin users. To accomplish this, I'm utilizing a data-table. Below is the code snippet I'm using: <v-data-table dense :headers="stampedDocumentsHeaders" :items="filterCutOffA ...