Creating unique IDs for movie pages with NUXT using data retrieved from the movie DB API

Here is the breakdown of my folder structure:

https://i.sstatic.net/X2CHX.png

This showcases how the page appears:

https://i.sstatic.net/Zul87.jpg

I have successfully retrieved all the necessary data from props. However, I am struggling to comprehend how to create dynamic id pages. The goal is to generate dynamic ~/movies/_id pages by extracting ids from an array obtained from an API. These generated pages should only fetch the Title, image, and overview information from the API object. These are the challenges at hand.

Movies.vue serves as the parent page. movieComp is a component utilized for v-for looping in order to display a list of movies fetched from the API's array. Each movie entry contains a details button beneath it, meant to direct users to individual movie details pages based on their respective ids fetched from the API.

_id.vue represents the page where content should be displayed according to the id received from the API.

Below is the code snippet from movies.vue (parent):

<template>
    <div class="flex flex-wrap min-h-full w-screen">
        <movieComp v-for="result in movies.results" 
          :key="result.id" 
          :movie-title="result.original_title" 
          :base-img-path="result.poster_path"
          :movie-id="result.id" />
    </div>
</template>

<script>
import movieComp from '../components/movieComp.vue'
export default {
  components: { movieComp },
    
    data() {
      return {
        movies: [],
        apiKey: "7ed6d2f608b8f66d8fd54d5f11c9e7d4",
        baseURL: "http://api.themoviedb.org/3/discover/movie?api_key=7ed6d2f608b8f66d8fd54d5f11c9e7d4",
        }
    },
    
    async fetch() {
      this.movies = await fetch(
        this.baseURL
      ).then(res => res.json())
      console.log(this.movies)

    },
    methods: {
    }
}
</script>

<style>

</style>

Next, we look at the code from movieComp (component, child):

<template>
  <div class="flex flex-col bg-gray-100 p-2">
      <h1 class="text-xl">{{movieTitle}}</h1>
      <img :src="'https://image.tmdb.org/t/p/w300'+baseImgPath" alt="Image">
      <nuxt-link :to="`/movies/${movieId}`" >Details</nuxt-link>
  </div>
</template>

<script>
export default {
  props: {
    movieTitle: {
      type: String,
      default: "Title"
    },
    baseImgPath: {
      type: String,
      default: "/464N3J1i6L5SsazPmX9m3q1GiZ3.jpg"
    },
    movieId :{
      default: 436969
    }
  },
  data (){
    return {
    }
  },
  methods: {
    
  }
  
  
  
}
</script>

<style>

</style>

Last but not least, let's examine the contents of _id.vue (located in the same pages folder as movies.vue):

<template>
  <div>
      <p>id is {{$route.params.id}}</p>
  </div>
</template>

<script>
export default {
    data() {
      return {
        movies: [],
        apiKey: "7ed6d2f608b8f66d8fd54d5f11c9e7d4",
        baseURL: "http://api.themoviedb.org/3/discover/movie?api_key=7ed6d2f608b8f66d8fd54d5f11c9e7d4",
        }
    },
    
    async fetch() {
      this.movies = await fetch(
        this.baseURL
      ).then(res => res.json())
      console.log(this.movies)

    },
}
</script>

<style>

</style>

Lastly, the following is a sample of the object retrieved from the API through the fetch request:

{
  page: 1,
  results: [
    { 
     ...
    },
    { 
     ...
    },
    
    // More entries here
    
    { 
     ...
    }
  ],
  total_pages: 500,
  total_results: 10000
}

Answer №1

To achieve this, simply create a new subfolder named "movies" and include two files within it: _id.vue and index.vue (which was previously named movies.vue).

Your folder structure should look like the following:

movies/
  index.vue (formerly known as movies.vue)
  _id.vue

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

Using AJAX and JQuery to automatically refresh a webpage on a scheduled interval

I am attempting to automatically refresh a page every 5 seconds with updated data from an SQL Server. Below is my code snippet: @model Test.Data.Domain.ManufacturingCdMachine @{ ViewBag.Title = "Rimage Details"; ViewBag.JobId = Model.CurrentManufa ...

Maintain the original order of rows in the table while shuffling the columns they appear in randomly

I need help with my table setup. The left column contains words in English, while the right column has the same words translated into Korean. Is there a way to keep the rows intact while randomizing the order of the columns? Here's an example: <ta ...

Exploring the possibilities of personalized attributes/directives in HTML and Javascript

My current challenge involves understanding how vue.js and angular.js handle custom directives in HTML. Suppose I have a div like this: <div my-repeat="item in items"></div> To replicate the functionality of vue.js, do I need to search throug ...

Comparing Optimistic Updates and Tag Invalidation in RTK Query

I found a basic code example from the RTK query documentation: updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({ query: ({ id, ...patch }) => ({ url: `posts/${id}`, method: 'PUT', ...

I am facing difficulty in loading another page due to AngularJS restrictions

How can I create a link that redirects to another page without any visible effect on the current page? I have tried various methods: <a href="url"> <a href="url" target="_self"> <a ng-click="register()"> The "register" function i ...

Can you explain the distinction between utilizing Object.create(BaseObject) and incorporating util.inherits(MyObject, BaseObject)?

Can you explain the difference between these two methods of setting the prototype? MyObject.prototype = Object.create(EventEmitter.prototype); MyObject.prototype = util.inherits(MyObject, EventEmitter); UPDATE I've noticed in various projects that ...

Executing a JavaScript file within the Meteor JS ecosystem

Is there a way to execute a JavaScript file on the server side in a meteor JS environment? Providing some background information: I am looking to automatically insert a document into a mongo database. While I know how to do this in meteor through event-dr ...

spinning camera around a globe with javascript and three.js

In my project, I am working on enabling a player to navigate in a first-person view on a planet using three.js and JavaScript. There are two key aspects I am focusing on: a) Implementing player movement around the planet, which involves two types of movem ...

Tips on ensuring the <script> section of a Vuejs single file component loads prior to the <template> section

After posing my query here, I have come to the realization that the root of my problem might be due to the template loading before the script. This causes an error when it encounters an undefined variable, halting the script execution. The issue could pote ...

Firebase functions are producing null values when called

I'm encountering an issue where the Functions function is returning null when I call it to retrieve user information. Can you provide a solution? workspace/functions/src/index.ts exports.getUser = functions.https.onCall((data, context) => { adm ...

Is there a way for JavaScript to automatically detect various display sizes and redirect users to different websites based on their screen dimensions?

I recently completed a new website and noticed that it looks quite strange on mobile devices, with overlapping divs causing issues. I tried implementing this code: window.addEventListener("resize", function(){ var width = window.innerWidth || ...

Addressing the Summer Note Problem within a Bootstrap Popup

I am currently facing an issue with the functionality of the Summernote Text plugin in my project. The text inside the Summernote editor does not display what I am typing until I resize the browser window. Below is the code snippet for reference: <%-- ...

Utilize Vue.JS to showcase JSON information from an external file

Currently, I have a View.JS app that displays a conversation thread from a JSON file. The existing code appears as follows: const app = new Vue({ el: "#app", data: { messages:[ { name: "Support", message: "Hey! Welcome to suppo ...

Personalize the File upload with HTML and Javascript

https://jsfiddle.net/yugxqopz/ I'm new to the world of UI and have a simple request: 1) I want to upload a document using an "attach file" option 2) Once the file is selected, I want to automatically trigger a specific JavaScript function as shown ...

Guide on transferring value from a <select> element using JavaScript

I'm attempting to pass the selected value of a <select> in the onChange function. I've explored this question on SO, but unfortunately, using this and this.value hasn't been successful. I understand that the question is quite old... se ...

Exporting variables in Node.js using module.exports

I am facing an issue with two JavaScript files, a1.js and utils.js. Here is the content of the files: a1.js const namet = require('./utils.js') console.log(name); utils.js console.log('utils.js'); const name ='Mike'; modul ...

Transferring UTM parameters to a different page via a button click

Is there a way to extract parameters from a URL after the "?" and add them to a button's href in order to redirect to another landing page? I want to transfer UTM parameters to another page using JavaScript within the button. Original Homepage: Dest ...

Creating a node server with Express allows for the seamless injection of dynamic HTML content into the index.html file using the res

I set up a mock node.js server using express and have created a dummy Index.html. The HTML file contains a simple form: <form action="/results" method="post" enctype="multipart/form-data"> <input type=" ...

The updates made to data in Vue.js are not reflecting on the screen

<template> <div class="parent"> <div class="container"> <h1 class="start" @click="start_timer"> {{ timerText }} </h1> </div ...

Maximizing Efficiency with React.js: Optimizing Value Calculation

Within my JSON, there are several fields that require calculation. I am unsure of the optimal location to perform these calculations. Currently, I have set them within: componentWillMount: function () { //Iterating over the JSON object } After calculat ...