How to save the value of `this.$route.params.id` in a Vue.js data property?

I am currently working with Vue.js 3 and have a sample code for routing and passing parameters.

Below is the Home.vue page:

<template>
  <div class="home">
    <h1>
      All Destinations
    </h1>
    <div class="destinations">
      <div v-for="destination in destinations" :key="destination.name">
        <router-link
          :to="{ name: 'DestinationDetails', params: { id: destination.id } }"
        >
          <h2>{{ destination.name }}</h2>
        </router-link>
        <figure>
          <router-link
            :to="{ name: 'DestinationDetails', params: { id: destination.id } }"
          >
            <img
              :src="require(`@/assets/${destination.image}`)"
              :alt="destination.name"
            />
          </router-link>
        </figure>
      </div>
    </div>
  </div>
</template>
<script>
// @ is an alias to /src
import store from "@/store.js";
export default {
  name: "home",
  components: {},
  data() {
    return {
      destinations: store.destinations
    };
  }
};
</script>
<style scoped>
.home {
  max-width: 1400px;
  margin: 0 auto;
}
img {
  max-width: 200px;
}
.destinations {
  display: flex;
  justify-content: space-between;
}
.vue-school-active-class {
  color: #ab26ab;
}
</style>

Clicking on the router link will take you to the DestinationDetails page along with sending the parameter id: destination.id

Next, here is the DestinationDetails page:

<template>
  <section >
     
    <h1>
      {{ destination.name }}
    </h1>
    <div class="destination-details">
      <img
        :src="require(`@/assets/${destination.image}`)"
        :alt="destination.name"
      />
      <p>{{destination.description}}</p>
    </div>
  </section>
</template>
<script>
import store from "@/store";

export default {
    
  data() {
    return {
      destinationId:this.$route.params.id
    };
  },
 
  computed: {
    destination() {
        return store.destinations.find(
        destination => destination.id === this.destinationId
      );
    }
  }
};
</script>

<style scoped>
img {
  max-width: 600px;
  height: auto;
  width: 100%;
  max-height: 400px;
}
.destination-details {
  display: flex;
  justify-content: space-between;
}
p {
  margin: 0 40px;
  font-size: 20px;
  text-align: left;
}
</style>

The issue I am facing with this code is that I'm unable to store the id from the route in the destinationId variable.

When I tried to simply read the route id on a blank template page using the code below, it worked fine:

<h1> Route: {{this.$route.params.id}} </h1> 
. However, storing it in the destinationId variable did not work. Can someone please help explain why this is happening?

Lastly, here is my store.js file:

export default {
  destinations: [
    {
      name: "Brazil",
      slug: "brazil",
      image: "brazil.jpg",
      id: 1,
      description:
        "all about Brazil... [insert long description here] ...turpis.",
      experiences: [
        {
          name: "Iguaçu Falls",
          slug: "iguacu-falls",
          image: "iguacu-falls.jpg",
          description:
            "...[insert long description here]... turpis."
        },
        ...
      ]
    },
    ...
  ]
};
   

Answer №1

Revised

$route.params by default returns a String, while your id in store.js is a Number.

As a result,

destination => destination.id === this.destinationId

will not yield the desired outcome.

To address this issue, you could either change the type of your id or switch the strict comparison from === to == for non-type checking.

Alternatively, you can manually convert your id into a String:

destination => destination.id === String(this.destinationId)

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

First experience with Django Bootstrap Modal Ajax was flawless, but on the second attempt, it was not as successful

I am currently utilizing Django 2.2 in conjunction with Bootstrap. The method implemented is as follows: Triggering the opening of a modal window, User updates the data, User saves the data, Underlying table from where the window originated is updated a ...

Trigger the UseEffect() function in a Material UI Dialog only when the dialog is open

In my project, I have a parent component that includes a Material UI Dialog as a child component. The purpose of this dialog is to fetch and display data from a REST API. Currently, I am using the UseEffect() function in the Dialog component to achieve th ...

Angular 13: A guide on pulling data from an Excel spreadsheet

I have been encountering issues while trying to display data from a CSV file on a web platform using Angular 13. The errors I am facing are related to binding 'ngModel' and type mismatches in the code. errors Error: src/app/app.component.html:24 ...

Merge nested arrays while eliminating any redundant elements

Is there a way to merge these array sets while ensuring that duplicate values are removed? I am unsure if lodash provides a solution for this specific scenario where the arrays are nested. Most of the solutions I have come across assume flat arrays. Any ...

PHP code for printing a JavaScript string containing a single quote

I'm encountering an issue with a script generated by PHP. When there is a single quote in the description, it throws a JavaScript error and considers the string terminated prematurely. print "<script type=\"text/javascript\">\n ...

Is it possible that the use of excessive React.Fragment could impact performance negatively?

After a recent review of our company's code, I discovered that the performance is not up to par. One common pattern I noticed in the code is something like this: condition ? <SomeComponent /> : <></> I see that Fragments are being u ...

When utilizing AJAX XMLHttpRequest, the concatenated response text from Symfony's StreamedResponse becomes apparent

Below is the code for a controller that returns Line 1 as soon as the endpoint is called and then two seconds later it returns Line 2. When accessing the URL directly at http://ajax.dev/app_dev.php/v2, everything works as expected. /** * @Method({"GET"}) ...

Juggling PHP scripts within javascript

Can you help me with a question I have? I am working on multiple JS scripts, such as this one: <script> $('#mapveto1').click(function() { $('#mapveto1').addClass('banned'); $('#map1').text('cobble ...

"Combining Angular and jQuery for powerful web development

I am looking to develop an application using Angular and incorporate numerous jQuery animations and jQuery UI effects (such as animate, fadeIn, fadeOut, etc). Is it feasible to use jQuery functions in conjunction with Angular? ...

The debounce function seems to be malfunctioning as I attempt to refine search results by typing in the input field

Currently, I am attempting to implement a filter for my search results using debounce lodash. Although the filtering functionality is working, the debounce feature seems to be malfunctioning. Whenever I input text into the search bar, an API call is trigge ...

Avoiding a constantly repeating video to prevent the browser from running out of memory

Using HTML5, I created a video that loops and draws the frames to canvas. I decided to create multiple canvases and draw different parts of the video on each one. However, after some time, I encountered an issue where Google Chrome would run out of memory. ...

Guide to implementing a dynamic v-model for input fields in Vue 2 and assigning values to this v-model

I've developed a unique component that generates dynamic input fields. One of the props it utilizes is called "fields." fields: [ { label: 'Question Text', placeholder: 'Enter Text', ...

Utilizing JavaScript for parallax horizontal scrolling (identifying optimal 50% of screen)

I have successfully implemented this code for vertical scrolling: $('.flapleftclass').css('top',(0+(scrolled*0.5))+'px'); This method works well because I am referencing to the top position. However, when it comes to horizon ...

Incorporate a PHP GET parameter through an onclick event to redirect using window.location in JavaScript when a button is

I am trying to modify the onclick event of buttons that look like this: <button class="buttons" onclick="window.location='page_test.php?VAR=1&VAR2=2'">BUTTON 1</button> <button class="buttons" onclick="window.location='p ...

Utilize JavaScript/jQuery to implement a prompt for saving downloaded files

https://i.sstatic.net/CVnPe.png Is it possible to use javascript or jquery to configure the setting mentioned above (Ask where to save each file before downloading)? ...

What is causing the poor color and contrast of equirectangular backgrounds in Three.js, and what steps can be taken to improve them?

Using Three.js for a website project with a construction company, I created 360° photospheres using my Google Pixel 5. The client also requested a 3D representation of one of their projects, making Three.js the ideal solution. Comparison: Original photo ...

React Hooks: Unable to re-enable input after it has been disabled

Attempting to manage the status of my points input whether it's enabled or disabled, I encountered an issue. Upon checking the checkbox, it correctly gets disabled. However, upon unchecking it, the input remains disabled. Initially, I attempted settin ...

Check out the ViewUI Vue.js component that expands to reveal more content!

Is there a simple component to create the expand/collapse button with a blur effect like in all the demos? I see it used across different variations of the demos and am wondering if there is a specific component or demo showcasing how to achieve this effec ...

The Challenge of Scope in JavaScript

I'm currently facing an issue with executing ajax requests using jQuery. The sequential order in which I am attempting this is as follows: Click the button Make an ajax post request Invoke a function that resides outside the current scope upon compl ...

Personalized Owl Carousel - OWL.JS Hover Pause Feature

I have been working on a slider in Codepen that is functioning well, and now I am trying to tweak it for my website. My goal is to make the carousel pause when someone hovers over it. I've experimented with all the options available on the owl slider ...