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

Tips for keeping a Bootstrap Modal in a fixed position on the screen as you scroll

I am facing an issue with a button that is supposed to trigger a Bootstrap Modal. It seems that the modal is not visible when the page has been scrolled down. Upon clicking the button to show the modal, the background darkens as expected, but the modal its ...

Nuxt disregards the usage of its own plugin

After attempting to install a plugin, I noticed that nothing happened. The install method was called. Just to clarify, this is just an example function in the plugin. In my nuxt.config.js file: ... export default { ... plugins: [ '~/plugins/mypl ...

The URL for the form action does not match the URL of the current page

Issue: I'm encountering an issue with a form where the form action URL is different from the page URL where the form is located. Page URL = www.page.com Form action = "" Problem: After submitting the form, it redirects to the form action URL inst ...

Navigating the intricacies of handling login with ajax

Essentially, the process of logging in typically unfolds as follows: The user inputs their information into the login form and submits it, The server (whether it be Ruby, PHP, Node.js, or any other) processes this data and either, a) redirects to the lo ...

A step-by-step guide on accessing grouped column data in Angular UI Grid

How do we access the data of all rows within a grouped column in Angular UI Grid? For instance, when looking at the Grouping Tutorial, how can we retrieve all the company names from the 'Company' column? I have successfully obtained the aggrega ...

Accessing Facebook through the React create app login

I recently developed a React Webapp using the create-react-app module. My current challenge involves integrating Facebook login, but I'm encountering some obstacles. I am unsure about where to incorporate the Facebook JavaScript SDK asynchronously to ...

set ajax url dynamically according to the selected option value

My form features a select box with three distinct choices <select id="tool" name="tool"> <option value="option1">Option1</option> <option value="option2">Option2</option> <option value="option3">Option3</ ...

What is the process for applying the source from an object while utilizing video-js?

I've been struggling to use a video player for streaming m3u8 videos. The code below works, but I want to dynamically set the source using an object. <video id="my-video" class="video-js" auto ...

What in the world is going on with this code snippet? I'm completely stumped on how to fix this problem

Attempting to generate a custom element with unique properties function y(){ var g=document.createElement("div"); this.label="elephant"; return g; } y.prototype.customFunction=function(){ alert(arguments[0]+this.label); }; var b=new y(); b ...

What is the best way to switch a Boolean value in React Native?

Struggling with toggling a Boolean state from true to false when the result is undefined. Tried several methods but none seem to work. The boolean state in the constructor is defined like this: class UserInfo extends Component{ constructor(props){ s ...

Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next. Initially, I considered calculating the time until each pers ...

Set a CSS rule to style every other row in a table, starting from the second row and resetting after

Is there a way to refresh the even and odd count in CSS whenever a specific row is shown? Here's an example setup: header header header even even even odd odd odd Subhead Subhead Subhead even even even How can I ensu ...

Custom HTML structure for WordPress navigation menu - WP Nav Menu

Need help creating a customized Wordpress Menu with HTML structure: <?php wp_nav_menu( array( 'theme_location' => 'global-menu' ) ); ?> The desired HTML output should resemble the following: <nav> < ...

A Node.js middleware that logs a message just once

My nodejs express app serves a file that requires and loads css files, js files, etc. I have implemented a logging middleware that retrieves the client's IP address and logs it (after cross-checking with a JSON file containing malicious IPs). Due to t ...

Why does my useEffect consistently execute after the initial rendering, despite having specified dependencies?

const [flag, setFlag] = React.useState(false) const [username, setUsername] = React.useState('') const [password, setPassword] = React.useState('') const [errorUsername, setErrorUsername] = React.useState(true) const [er ...

Position the text alongside the Facebook emblem

I am having trouble getting the text Follow Us to align on the far right next to the Facebook Icon. I added the float:right property, but it is not working as expected. Here is the code snippet: <a href="#" target="_blank" style="font-family: Arial, ...

The Mongoose connection keeps failing to reconnect and maintain a stable heartbeat

I am facing an issue with the automatic reconnection feature in mongoose on my project. Despite configuring it to reconnect after a certain interval, it does not work as expected. Even if the credentials are correct, mongoose should attempt to log in perio ...

Guide on seamlessly adding NPM "dependencies" to index.html using <script> tags in a VUE JS WEBPACK project

Are there any tools available that automatically inject or include NPM dependencies into the index.html file, similar to the GRUNT-BOWER plugin for BOWER dependencies? The project in question is a VUE-CLI WEBPACK project. Can this functionality be achieve ...

Issue: ui-route failing to function properly when the href attribute is utilized

I am currently working on implementing ui-route to manage the states of my app while focusing on URL navigation. My goal is to enable users to simply click on a link and be directed to the state associated with the specific URL. After following an In-Dep ...

React Native - Implementing a dynamic form that adapts based on the answer given by its parent

My JavaScript Object has a simple state structure as follows: pertanyaan: [{ label: "label1", type: 'dropdown', key: 'keyFoo1', option: [{ value: "foo1" }, { value: "foo2", additional ...