Is there a way to pass locale data using props in VueJS Router?

To access hotel data, the URL path should be localhost:8080/hotel/:id (where id is equal to json.hoteID).

For example, localhost:8080/hotel/101

This path should display the specific data for that hotel.

In order to achieve this, we will utilize VueJS vue-router.

import json from "@/assets/data/Hotels.json";
data() {
    return {
      data: json,
    };
  },

Answer №1

To retrieve the hotelID, you can access it through $route.params. Refer to the documentation for more details. Once you have the ID, you can find the corresponding hotel data in Hotels.json using $route.params.id. Check out the Demo

Hotels.json

{
  "hotels": [
    {
      "id": 1,
      "name": "hotel 1"
    },
    {
      "id": 2,
      "name": "hotel 2"
    },
    {
      "id": 3,
      "name": "hotel 3"
    }
  ]
}

router.js

const routes = [
  {
    path: "/",
    name: "hotels",
    component: function () {
      return import("@/components/Hotels.vue");
    }
  },
  {
    path: "/hotel/:id",
    name: "hotel",
    component: function () {
      return import("@/views/Hotel.vue");
    }
  }
];

App.vue

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Hotels</router-link>|
      <template v-for="(item, key) in hotels">
        <router-link :key="key" :to="`/hotel/${hotels[key].id}`">{{
          hotels[key].name
        }}</router-link
        >|
      </template>
    </div>
    <router-view />
  </div>
</template>

<script>
import json from "./Hotels.json";
export default {
  name: "App",
  data() {
    return {
      hotels: json.hotels,
    };
  },
};
</script>

Hotel.vue

 <template>
   <div>
     <h1>{{ hotel.name }}</h1>
   </div>
 </template>

    <script>
    import json from "../Hotels.json";
    export default {
      data() {
        return {
          hotels: json.hotels,
        };
      },
      computed: {
        hotel() { 
          return this.hotels.find((item) => item.id === +this.$route.params.id);
        },
      },
    };
    </script>

Answer №2

Using the Vue.js framework, this code navigates to a specific route by pushing a new object into $route with the parameter id set to hotelID from data.

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 process of using AJAX, JavaScript, and HTML to submit data to a remote

I need help with sending data from an HTML page to a server. I have a JSON example below that illustrates what I want to achieve. On my HTML page, I have a question label and four options (A, B, C, D) as radio buttons. After clicking the send button, I ...

Angular 6 TypeScript allows for efficient comparison and updating of keys within arrays of objects. By leveraging this feature

arrayOne: [ { id: 1, compId: 11, active: false, }, { id: 2, compId: 22, active: false, }, { id: 3, compId: 33, active: false, }, ] arrayTwo: [ { id: 1, compId: 11, active: true, }, { id: 2, compId: 33, active: false, ...

Customize.Print - establish default print preferences

In my current project, I am exploring ways to add a print PDF feature. After discovering print.js, it seems like a possible solution for this task. My main concern is setting default print options to ensure the correct scale (i.e., 100%). Does print.js h ...

What is the best way to eliminate mouse click release events?

Encountering an issue with my Vue/Vuetify Dialog that closes when clicking outside of it as expected. The problem arises when there is a text field inside the dialog. If I accidentally select the content and release the mouse outside of the dialog, it als ...

Ensuring even distribution of three divs within a container

Imagine a container that is 1200px wide, with three divs inside. Each div is only 292px wide. The first div should align with the left margin, the third div with the right margin, and the second div should sit right in the middle of them. Adding to the c ...

What is the best way to iterate through a collection of two or more arrays in order to determine the total length of all

https://i.stack.imgur.com/PpFlB.pngI currently have multiple Arrays containing various inputs this.listNumber = [ { "GenericQuestions": [ { "input": "long", }, { "input": & ...

Ensuring IconButton is perfectly aligned with Text in one straight line

I want to display IconButtons alongside plain text in a single block of text, but the result didn't turn out as I had hoped. Here is what I attempted: JS(ReactJS): <div> <span> <h3>Title</h3> <IconButton className ...

Leveraging PHP variables to determine the image location, implement an onclick function to cycle through the image gallery

I am facing an issue with a database query that is supposed to display multiple images. These images are stored in a PHP variable and shown one at a time using a JavaScript gallery with an onclick function to navigate through them. Unfortunately, the funct ...

Unable to utilize a computed property within the data section

I am working with an array in my data: data () { return { steps: [ { disabled: this.someCheck } ] } } Additionally, I have a computed property: computed: { ...mapGetters({ getFinishedSteps: 'jobFound/getFinishedS ...

Error: The property 'slice' cannot be read from an undefined value

I am currently working on a prototype recipe app called Forkify, which is being developed using Javascript, NPM, Babel, and Webpack. In this project, I am utilizing a custom API. API URL : forkify-api.herokuapp.com TO SEARCH RESULT This API returns a l ...

What is the best way to create a case-insensitive search feature in Node.js?

I have implemented a search function that takes input from the client as Str. If it matches with content in a file, I send that response. For example, if I have text in a file labeled Lorem, and the client searches for lorem, it returns an empty array due ...

Generating observables from form submission event

Note: I am completely new to Angular and RXJS. Currently, I am working on a simple form where I want to create an observable. The goal is to listen for submit events and update a value within the component. However, I keep encountering an error message sa ...

How can I dynamically update the sidebar in Ionic 3 post-login without the need to reload the app or refresh the browser?

I have successfully implemented login and sign up functionality in my ionic 3 app. However, I am facing an issue where the username is not updating in the sidebar instantly after logging in. Currently, I need to refresh the browser or close and reopen the ...

Unspecified data transfer between child and parent components

I'm working on implementing a file selection feature in my child component, but I'm facing difficulties passing the selected file to the parent component. I'm struggling to find a solution for this issue and would appreciate some guidance. W ...

Tips for extracting information from a website with Selenium using Python

I am currently working on a project that requires me to extract certain information using Selenium from a webpage. The elements I need are not directly visible in the page's code, indicating they may be generated by JavaScript. Here is a snippet of my ...

Grasping the idea of elevating state in React

I can't figure out why the setPostList([...postList, post]) is not working as expected in my code. My attempts to lift the state up have failed. What could be causing this issue? The postList array doesn't seem to be updating properly. I'v ...

How to Perfectly Center a Div using CSS in Next.js (slightly off-center)

Despite scouring numerous StackOverflow questions, I haven't been able to find a solution that fits my specific issue. It seems like there might be a CSS attribute preventing the div from centering properly. Could utilizing flexbox help resolve this? ...

Using both Promise based architecture and events in Node.js can lead to unexpected behavior and should be avoided

Currently, I am developing a nodejs application that is expected to grow in size. Despite my efforts, I have not been able to find many resources on advanced Nodejs project architecture and structure. I am wondering if it would be considered bad practice ...

Having trouble establishing a web socket connection using JavaScript

I'm experiencing an issue trying to connect my web socket to an Amazon instance using a specific IP address. I've had success connecting the web socket with a different IP and port using the Google Rest Client app, but now when I try to connect w ...

Struggling to achieve desired output from function in NextJS

I'm a bit confused by the code below. The itmLoop function seems to work fine when placed directly in the return section, but nothing is output when it's called as shown below? I'll eventually need to make it recursive, so I have to keep i ...