vue-router incorrectly updates parameters upon reload

One question I have is related to routing in Vue.js:

// routes.js
{ path: '/posts', name: 'Posts', component: PostsView },
{
    path: '/post/:post_id',
    name: 'PostRead',
    component: PostReadView,
},
{
    path: '/post/cu/:post_id?',
    name: 'PostCreateUpdate',
    component: PostCreateUpdateView,
},
// PostCreateUpdate.vue
mounted: function() {
    if( this.$route.params.post_id ) {
        this.$store.dispatch('getPost', this.$route.params.post_id);
    }
},

My dilemma arises when accessing the PostCreateUpdate component through a router-link:

<router-link :to="{ name: 'PostCreateUpdate' }">Create</router-link>

Everything works smoothly, but when reloading the page or directly altering the URL to /post/cu/, an unexpected behavior occurs. The framework seems to interpret "cu" as a parameter for /post/, leading to the wrong component being loaded with incorrect data. How can I prevent this issue?

Answer №1

It is crucial to always prioritize your most restrictive URIs in the Vue Router configuration. The order of routes matters significantly, as Vue Router will sequentially check each route and select the first one that matches.

To ensure proper routing, switch the order of your /post/:post_id route and /post/cu/:post_id? route:

// routes.js
{ path: '/posts', name: 'Posts', component: PostsView },
{
    path: '/post/cu/:post_id?',
    name: 'PostCreateUpdate',
    component: PostCreateUpdateView,
},
{
    path: '/post/:post_id',
    name: 'PostRead',
    component: PostReadView,
},

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

Create PDFs using PhantomJS when the HTML content is fully loaded and ready

I am a newcomer to utilizing phantomjs and encountering difficulties in rendering my website as a PDF file. Although I can successfully render a simple version of the page, issues arise when multiple images and web fonts are involved, causing the DOM not t ...

Having trouble compiling a Vue.js application with TypeScript project references?

I'm exploring the implementation of Typescript project references to develop a Vue application within a monorepo. The current structure of my projects is outlined below: client/ package.json tsconfig.json src/ ... server/ package.json t ...

managing the reloading of pages and navigating back and forth in the browser

In my project, I am using react and next.js to make API requests from a search bar and display a list of movies on the homepage. Each search result redirects me to a different page that shows detailed data related to the selected movie. However, the issue ...

Using the `ng-if` directive in Angular to check for the

I need to output data in JSON format using items. To display a single item, I utilize ng-repeat="item in items". Additionally, I can access the user object of the currently logged-in user with user. Every item has the ability to belong to multiple wishlis ...

Having trouble decoding invalid JSON received from the Twilio API

For the past 4 hours, I've been struggling to parse a basic JSON from Twilio. The process is as follows: A text message containing a magnet link is sent Twilio forwards the request to my serverless function in the cloud I attempt to parse the reques ...

Adding a character to an AngularJS textbox

I am attempting to add the "|" Pipe symbol to a textbox when a button is clicked, using this function. $scope.appendPipe = function(){ var $textBox = $( '#synonyms' ); $textBox.val($textBox.val()+'|'); //textBox ...

The transformation in the resulting array is evident when a nested array is altered after being concatenated using Array.concat

MDN explains concat as follows: The concat() function is utilized to combine two or more arrays without altering the original arrays. Instead, it produces a new array. Let's examine the code snippet below: Example 1 const array1 = [['a& ...

There are two different ways to set a hyperlink in HTML. One method is by using the href attribute, where you provide the URL inside the quotation marks. The other

While browsing, I stumbled upon this interesting piece of JavaScript code: onClick="self.location.href='http://stackoverflow.com/'" I incorporated this code into my website, and it seems to have the same effect as using the href attribute. Sin ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...

Navigating with Google Maps and Its Pointers

I've successfully integrated a JSON array of Marker positions into a Google map. Each marker has an associated infoWindow, which is also functioning as expected. However, I'm encountering an issue where clicking on a marker only displays the in ...

An error message 'module.js:557 throw err' appeared while executing npm command in the terminal

Every time I try to run npm in the terminal, I encounter this error message and it prevents me from using any npm commands. This issue is also affecting my ability to install programs that rely on nodejs. $ npm module.js:557 throw err; ^ Error: Cannot ...

Unable to properly access required file path through HTML source

I have a confidential folder named 'inc' where I store sensitive files such as passwords in php connection files. This folder is located at the same level as the 'public_html' folder. I successfully accessed php files with database conn ...

What is the purpose of including an es directory in certain npm packages?

Why do developers sometimes have duplicated code in an es folder within libraries? Here are a few examples: https://i.stack.imgur.com/BWF6H.png https://i.stack.imgur.com/3giNC.png ...

Angular code is malfunctioning and not delivering the expected results

I currently have setup the code below: var videoControllers = angular.module('videoControllers', []); videoControllers.videoControllers('VideoDetailController', function($scope, $routeParams, $http){ $http.get('http://localho ...

What is the best way to populate empty dates within an array of objects using TypeScript or JavaScript?

I am trying to populate this object with dates from today until the next 7 days. Below is my initial object: let obj = { "sessions": [{ "date": "15-05-2021" }, { "date": "16-05-2021" }, { "date": "18-05-2021" }] } The desired ...

Issue when attempting to animate an SVG point using translateX transformation

I am attempting to create a basic animation using the translate X property on a section of my svg when hovering over the element. Here is the code I have so far: <html> <style> .big-dot:hover { transform: translateX(20px); animat ...

React - utilize a variable as the value for an HTML element and update it whenever the variable undergoes a change

I'm on a mission to accomplish the following tasks: 1.) Initialize a variable called X with some text content. 2.) Render an HTML paragraph element that displays the text from variable X. 3.) Include an HTML Input field for users to modify the content ...

The second parameter of the filter function is malfunctioning

I'm currently delving into the "filter" function in AngularJS. Upon reviewing the documentation, I've discovered that it can also take a second parameter. When set to "true", it carries out a strict comparison. HTML <fieldset> <leg ...

Error occurred in next.js environment file when referencing process.env keys as strings in .env.local file

I have a .env.local file with various values stored in it. NEXT_PUBLIC_GA_ID = myvariablevalue I created a function to validate the presence of these values: export const getEnvValue = (name: string, required = true) => { const value = process.env[na ...

Show/hide functionality for 3 input fields based on radio button selection

I need assistance with a form that involves 2 radio buttons. When one radio button is selected, I want to display 3 text boxes and hide them when the other radio button is chosen. Below is the code snippet: These are the 2 radio buttons: <input type= ...