Tips for updating a single parameter with vue router-link

I am facing an issue with my user list and calendar components. Whenever I click on a user link, I want only the selectedUser parameter in the URL to change while leaving all other parameters unchanged.

Currently, when I click on the "Change date" link, it updates the date. However, if I then click on a user link, it still shows the old date that was rendered previously.

URL: /users/John/month/2019/01 after clicking on "Change date" - /users/John/month/2009/09

Subsequently, clicking on a different user reverts back to the old date like so: /users/Bob/month/2019/01

The user link code is as follows:

<li v-for="user in users">
    <router-link
        :class="{ active: user.id == selected }"
        :to="{ name: 'MainRoute', params: { selectedUser: user.id }}">
        {{ user.username }}
    </router-link>
</li>

On the other hand, the calendar link for changing dates looks like this:

<router-link
    :to="{ name: 'MainRoute', params: { selectedMonth: '09', selectedYear: '2009' }}">
    Change date
</router-link>

Below is my routes object configuration:

{
    name: 'MainRoute',
    path: '/users/:selectedUser/:selectedView/:selectedYear/:selectedMonth',
    ...
}

Answer №1

If you need to access the actual route parameters, you can do so by using $route.params. You could potentially utilize it in this manner:

  <li v-for="user in users">
    <router-link
    :class="{ active: user.id == selected }"
    :to="{ name: 'MainRoute', params: {selectedUser: user.id,
         selectedView :$route.params.selectedView,
         selectedMonth: $route.params.selectedMonth, 
         selectedYear: $route.params.selectedYear}}">
    {{ user.username }}
    </router-link>
  </li>

Answer №2

  <li v-for="user in users">
    <button @click="modifySelectedUser('selectedUser', user.id)">
      {{ user.username }}
    </button>
  </li>

modifySelectedUser function:

methods: {
    modifySelectedUser(paramName, newValue) {
        let currentParams = this.$route.params
        currentParams[paramName] = newValue
        this.$router.push({ name: this.$route.name, params: currentParams })
    }
}

Answer №3

It appears that modifying the this.$route object directly is not permitted. It seems a new copy of it is necessary:

this.$router.push({ 
        name: this.$route.name,
        query: {...this.$route.query, [name]:value}
    });

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

Struggling to showcase API data on React interface

I am working on fetching data from a private API and displaying it on a web page. My frontend is built using React JS, while my backend uses Node with Express and Axios. Everything seems to be working fine until the point where I need to display the fetche ...

Get the page downloaded before displaying or animating the content

Is there a method to make a browser pause and wait for all the content of a page to finish downloading before displaying anything? My webpage has several CSS3 animations, but when it is first loaded, the animations appear choppy and distorted because the ...

What steps are involved in creating an xlsx file using Express and Exceljs, and then sending it to the client?

I am currently working on separating controllers and services in my Express app. One of the services I have generates an XLSX file using ExcelJS. I'm looking for a way to reuse this service without passing the response object to it. Is there a method ...

Vue.js: crafting a universal composable is proving challenging

I am faced with the challenge of making a universal composable. In my scenario, I have 3 components - ItemSwiper, ItemCard, and ViewRecipeDetail. ItemSwiper contains card slides and serves as the parent of ItemCard. The loop of recipes in ItemSwiper loo ...

What is the best way to automatically show scrollbars when a page loads using JavaScript?

How can I make the vertical scrollbar appear as soon as the page loads using javascript? I am currently using a jquery slide toggle animation that causes the vertical scrollbar to show up because it makes the page longer. However, when the scrollbar appear ...

In Laravel, Inertia.js will automatically close a modal if there are no validation errors present

Here is the method I am currently using: methods: { submit() { this.$inertia.post('/projects', this.form); this.openModal = false; }, }, Unfortunately, this method closes the modal even if there are validation erro ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

Simply close by clicking outside using basic vanilla JavaScript

I have successfully implemented a menu that closes (removes the added class) when clicking outside the menu button area. Although it is working fine, I am unsure if my code is correct. My understanding is that the click outside functionality should only b ...

Achieving dynamic height in a parent div with a sticky header using mui-datatables

Here are the settings I've configured for my mui-datatables: const options = { responsive: "standard", pagination: false, tableBodyHeight: '80vh', }; return ( <MUIDataTable title={"ACME Employee ...

What is causing ngResource to change the saved object to something like "g {0: "O", 1: "K", ..} once it receives a response?

In my current setup, I have a default ngResource that is defined in the following way: var Posts = $resource('/posts/'); Once I retrieve a blog post from my nodejs server using the code below: $scope.post = Posts.get({_id:query._id}); The use ...

Can you explain the variance between calling mongoose.Schema() and creating a new instance with new mongoose.Schema()?

Can you explain the distinction between mongoose.Schema() and new mongoose.Schema() methods? I have tried both approaches, and it seems like they yield similar results. Are there any notable differences or implications to consider? ...

Define JSON as writeable: 'Error not caught'

I'm facing an issue with a read/write error in my JavaScript code because the JSON file seems to be set as read-only ('Uncaught TypeError: Cannot assign to read only property'). How can I change it to writable? Should I make changes in the J ...

Utilizing a dropdown list in HTML to dynamically change images

On my HTML page, I have implemented a dropdown list box. My objective is to change an image and update a label based on the selection made from the dropdown list box. I already have an array called 'temp' which represents the number of items. The ...

RequestDispatcher.forward() does not work when servlet is invoked through an Ajax POST request

My login page involves user authentication through the firebase and sending the request to a servlet. When I click the submit button with correct credentials, the firebase authentication works, the servlet is called but an error is displayed in the browser ...

Ways to retrieve and bind data using onMounted in VueJS

Loading Data in Test.vue Component <template> <li v-for="item in masterCompany" v-bind:key="item.id"> {{ item.displayName }} </li> </template> <script> import Test from "../hooks/Test.hook" ...

In certain Express app files, the use of Sequelize modules may result in a return value of undefined

Objective - To implement a middleware-like callback in userHandler located in util.js for certain express routes in an express app, created using express-generator and sequelize-cli. Expected Outcome - Utilize the user model successfully in routes and use ...

Exploring Angular.js: Finding the correct path in a JSON array

Within my Angular application, I have a $scope variable defined as follows. $scope.roleList2 = [ { "roleName" : "User", "roleId" : "role1", "children" : [ { "roleName" : "subUser1", "roleId" : "role11", "collapsed" : true, "children" : [ ...

Is Highcharts-angular (Highcharts wrapper for Angular) compatible with Angular 4?

I have attempted to install various versions of highcharts-angular, ranging from 2.0.0 to 2.10.0. However, I consistently encounter the same error when running the application. The error message states: Metadata version mismatch for module C:/dev/Angular- ...

Can a Vue component be created using a for loop within a function?

Have you ever tried generating a Vue component using a for loop? I attempted to create and retrieve it, but it seems to be overridden by a new component dynamically. The first component's schema is being overwritten by the schema of the second compone ...

Determining the visibility of an element on a webpage using JavaScript and Puppeteer

I've created a framework that scans websites hosted on our servers to ensure they comply with our policies. If any prohibited content is found, we capture a screenshot along with other relevant details. However, taking a screenshot may not be possibl ...