Utilizing fixed JSON data for dynamic routing in Vue.js

I have a local JSON file that contains all my content. With the help of VueResources and VueRouter, I am trying to create a list component to display items from this local JSON file. The goal is to show the content of a clicked item on another page using $route.params.

Below is my list component called Objects.vue

<template>
  <div id="objects">
    <router-link :to="'/' + this.lists.id"><div v-for="(item, index) in lists" class="list">{{ item.title }} {{ item.id }}</div></router-link>
  </div>
</template>

<script>
//import json from './../assets/data.json'
export default {
  name: 'Objects',
  data() {
    return {
      lists: [],
    };
  },
  methods: {
    getObjects() {
       this.$http.get('/static/data.json')
          .then((response) => {
            console.log(response.body);
            this.lists = response.body.objects;
          })
    }
  },
  mounted() {
    this.getObjects();
    console.log(this.lists.id);
  }
};
</script>

<style scoped>

</style>

Here is my item component named Object.vue

<template>
  <div id="object">
    <div>
      {{ object.id }}
    </div>
    <div>
      {{ object.title }}
    </div>
  </div>
</template>

<script>
import json from './../assets/data.json'
export default {
  name: 'Object',
  data() {
    return {
      id: this.$route.params.id,
      object: {},
    };
  },
  methods: {
    getObjects() {
       this.$http.get('/static/data.json/' + this.id)
          .then((response) => {
            console.log(response);
            this.object = response.body.objects;
          })
    }
  },
  mounted() {
    this.getObjects();
  }
};
</script>

And this is what my json file looks like:

{
  "objects": [
    {
      "id": 0,
      "title": "a"
    },
    {
      "id": 1,
      "title": "b"
    },
    ...
    {
      "id": 9,
      "title": "j"
    }
  ]
}

Contents of route/index.js file can also be found below:

...

The list component displays all items correctly but when an item is clicked, the id returns as undefined. If you click an item, it leads to http://localhost:8080/undefined

How can I fix this issue? What am I missing?

Answer №1

this.lists.id is always undefined. Our this.lists consists of an array. It is recommended to place the router inside a v-for loop and access item.id.

The correct approach should be:

<div v-for="(item, index) in lists" class="list" :key="item.id">
  <router-link :to="'/' + item.id">
   {{ item.title }} {{ item.id }}
  </router-link>
</div>

Updated Version:

After thorough discussion, it is advisable to update your Object.vue component as follows:

<template>
  <div id="object">
    <div>
      {{ object.id }}
    </div>
    <div>
      {{ object.title }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'Object',
  data() {
    return {
      id: this.$route.params.id,
      object: {},
    };
  },
  methods: {
    getObjects() {
       this.$http.get('/static/data.json')
          .then((response) => {
            console.log(response);
            this.object = response.body.objects.find(item => item.id == this.id)
          })
    }
  },
  mounted() {
    this.getObjects();
  }
};
</script>

Alternatively, you can directly import data from data.json like so:

<template>
  <div id="object">
    <div>
      {{ object.id }}
    </div>
    <div>
      {{ object.title }}
    </div>
  </div>
</template>

<script>
import json from './../assets/data.json'
export default {
  name: 'Object',
  data() {
    return {
      id: this.$route.params.id,
      object: {},
    };
  },
  mounted() {
    this.object = json.objects.find(item => item.id == this.$route.params.id)
  }
};

</script>

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 proper method for overriding styles in material-ui v5 for properties that are not present in the themes components?

Currently, I am customizing MuiDataTables using the adaptv4theme in the following manner: declare module '@material-ui/core/styles/overrides' { export interface ComponentNameToClassKey { MUIDataTable: any; MUIDataTableFilterList: any; ...

Extracting data from the response object and injecting it into the request

Once the file has been successfully uploaded, the 'uploadSuccess' callback event is triggered, providing information about the newly created media. The 'hashed_id' value within this object is crucial for my PUT request. I attempted to ...

Enhance the functionality of Map.set by automatically storing the new entry on the disk as well

This code is intended for development purposes only, to resume work from where I left off when restarting the local server. I aim to avoid modifying the production code in any way. My goal is to save new entries to disk when using map.set(...). Below is a ...

Guide to transferring text to clipboard using PHP and JS

Forgive me if this sounds a bit silly. I've been trying to figure this out for a while now, and it seems like the only solution I found involves clicking some sort of button. I have a form that generates license keys, and after generating one, I wan ...

Tips for effectively organizing a collapsible list

Here is a list that I have: <ul> <li><span class="Collapsable">item 1</span> <ul> <li><span class="Collapsable">item 1.1</span></li> </ul> </ul> I am looking to create ...

Refresh the jQuery widget tab's div after the table update is complete

I am implementing a jQuery tab that shows table data with an editing function using Lytebox for pop-up forms. The issue I'm facing is the need to refresh the page to update the content, which confuses me regarding the URL and the update process. I hav ...

Designing a Curved Stepper Component in the Shape of an S

I've been attempting to create a custom stepper component with an S-curve shape using React, but so far I haven't been successful. I even tried utilizing the MUI Stepper component and experimented with pure HTML and CSS, but couldn't achieve ...

Retrieve the source code of a webpage by accessing its URL with JavaScript through the use of JSONP

To extract the source code from a URL web page using JSONP, you can use the following code snippet: <script type="text/javascript"> var your_url = ''; $(document).ready(function(){ jQuery.ajax = (function(_ajax){ var protocol = location. ...

A guide to fetching MongoDB data and presenting it in a table with ReactJS

I’m currently facing an issue while trying to display data from my MongoDB database in a table using ReactJS. Instead of getting the expected outcome, all I see is an empty result on the webpage along with some errors shown in the browser console. https ...

Verify for any empty values in a quiz

After completing a quiz using vue.js, I am facing a challenge in checking if a value is null before logging it into console.log. I have been unable to find a solution for this issue. Although I have numerous questions to include in the quiz, some of them ...

Manipulating the Document Object Model (DOM) in Google

I typically implement this method to ensure that users adhere to the validation rules before submitting. <a class="waves-effect waves-light btn disabled">Submit</a> But, I recently discovered that by simply removing the disabled class using G ...

Encountered an issue with resolving the module specifier while utilizing a Web Component

I recently added the @tokens-studio/configurator package from NPM to my project. However, upon importing it as instructed, I encountered the following error: Failed to resolve module specifier "@tokens-studio/configurator". Relative references m ...

Having issues with my jQuery getJSON function

Encountering a familiar issue once again. I am currently in the process of modifying a function that previously returned an object in the code. Now, I am attempting to retrieve the object from JSON using $.getJSON function getEventData() { var result = ...

Discovering hidden Mixed Content problems on a secured website can be a challenging task

After deploying a simple PWA application on the NGINX server, which was created using Vue CLI, I decided to use hash mode instead of history mode for the Vue router. Even though the website is secure: https://i.sstatic.net/CLfUr.png I am encountering th ...

Navigating with Vue Router on Internet Information Services (IIS)

I am encountering difficulties understanding why my routes are failing when I refresh my VueJS application hosted on IIS. Everything works fine during normal browsing, but once I press F5 or update view information through a button, a 403 error is thrown. ...

display different vue component based on screen size

I am in search of a method to implement responsive components in Vue.js (Nuxt). I have developed this mix-in but encountering an error: export const mediaQuery = { data() { return { breakpoints: { sm: 576, md: 768, lg: ...

Combining multiple JSON objects in an array into one single object with the help of jQuery

My array consists of JSON objects like the ones shown below: [{ "Name": "Nikhil", "Surname": "Agrawal" }, { "profession": "java developer", "experience": "2 years" }, { "company": "xyz", "city": "hyderabad" }] What I aim to achiev ...

Using VueMultiselect with Vue 3: A guide for beginners

I'm currently experimenting with the vue multiselect component, but when I include it in the template, I am encountering a series of warnings and errors. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

Using Vue JS to display information conditionally within a single component

I currently have a component that dynamically displays the data from an array of objects. However, I want the component to display only one object based on a specific condition. Is it possible to show either one object or another depending on the value o ...

Using AngularJS to create multiple sets of parent-child tabs and dynamically setting a specific tab as

Working with angularjs in this scenario: I have 2 primary tabs and each of these tabs can contain one or multiple nested tabs. The code snippet is as follows: <tabset class="tabbable-line"> <tab ng-repeat="(key,value) in tabsData" heading=" ...