Exploring the integration of dynamic URLs in Nuxt.js using DRF

After receiving guidance on integrating information from DRF into Nuxt.js, I find myself eager to learn more. I followed the basic instructions but still struggle to grasp the concept. Can anyone offer a solution to this issue?

I am particularly interested in creating dynamic pages and came across an example on Nuxt.js dynamic page routing. How can I implement this effectively? The tree path structure is as follows:

pages

-- _catname

---_product.vue

index.vue

_id.vue

Apologies for the numerous questions, as I am a beginner seeking clarification.

My code for _product.vue is as follows:

<template>
  <div>
    <h1>CAT NAME: {{ catname }}</h1>
    <h2>Product ID: {{ id }}</h2>
    <p>Path: {{ $route.path }}</p>
    <NuxtLink to="/">Back to All Product</NuxtLink>
  </div>
</template>
<script>
export default {
  async asyncData({ params, redirect }) {
    const products = await fetch(
      'http://127.0.0.1:8000/product_api/api/v1/Product/'
    ).then((res) => res.json())

    const filteredproducts = products.results.find(
      (el) =>
        el.catname === params.catname &&
        el.id === params.id
    )
    if (filteredproducts) {
      return {
        catname: filteredproducts.catname,
        product: filteredproducts.name
      }
    } else {
      redirect('/')
    }
  }
}
</script>

And my code for _id.vue is as follows:

<template>
  <h1>{{ this.id }}</h1>
</template>

<script>
  export default {
   async asyncData({ params }) {
      const id = await params.id // When calling /abc the slug will be "abc"
      return { id }
    }
  }  
</script>

Answer №1

It is recommended to utilize the this keyword within the template.

Please share any errors you are encountering and your desired outcome.

Answer №2

├─Pages
    ├────index.vue
    ├────_product.vue
    ├────_catname.vue
    ├────_id.vue

If you have the file structure mentioned above, then in the case of _product.vue it only has a parameter called product. Therefore, the product can be filtered by using params.product only. Below is the code snippet:

<template>
  <div>
    <h1>CAT NAME: {{ catname }}</h1>
    <h2>Product ID: {{ id }}</h2>
    <p>Path: {{ $route.path }}</p>
    <NuxtLink to="/">Back to All Product</NuxtLink>
  </div>
</template>
<script>
export default {
  async asyncData({ params, redirect }) {
    const products = await fetch(
      'http://127.0.0.1:8000/product_api/api/v1/Product/'
    ).then((res) => res.json())

    const filteredproducts = products.results.find(
      (el) =>
        el.id === parseInt(params.product)
    )
    if (filteredproducts) {
      return {
        catname: filteredproducts.catname,
        product: filteredproducts.name
      }
    } else {
      redirect('/')
    }
  }
}
</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

Why isn't the transparency feature in graphicsmagick working?

Currently, I am utilizing the graphicsmagick npm package which can be found at https://www.npmjs.com/package/gm. In my attempt to write a piece of code similar to the one below, I am struggling to make it function properly with stream. The image file myimg ...

When a POST request fails, which AJAX event is triggered?

How can you handle a failed post request in jQuery AJAX? Suppose the site shows this message: POST http://s-t-h-c.appspot.com/dispatch 500 (Internal Server Error) which AJAX event should you use to address it? In case of a successful request, we typicall ...

How can I adjust the column width in OfficeGen?

Currently, I am utilizing officeGen for the purpose of generating word documents. <sup> let table = [ [ { val: "TT", fontFamily: "Times New Roman", }, { val: "Ten hang", ...

Confirm the object received from the API and assign default values

Seeking to extract data from an API and verify if all fields are strings, but if they are missing I aim to assign default values. My intention was to utilize the yup library to validate the object accordingly, ensuring that the returned function is prope ...

Tips for making a bookmark for your iframe content

Within this HTML code, there is a list element with the ID "about_ma" and an iframe named "page" that is initially hidden. <div id="navigation"> <ul id="nav"> <li id="about_ma"><a href="index1.php?name=about.php">Ab ...

The powerful combination of Laravel 10, Inertia, Vue 3, Vite, and the convenience of self-hosted

I'm having trouble integrating TinyMCE as a self-hosted solution. Despite following the steps outlined at this link, the editor still fails to load in a self-hosted manner and prompts for a key: After struggling with this issue for two days without s ...

What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3. In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3. I want to dynamically pu ...

Merge identical year items into a single entity

I have an array of objects containing car data: [ { year: 2019, company: 'Toyota', quantity: '450' }, { year: 2019, company: 'Ford', quantity: '600' }, { year: 2020, company: ...

The validation of pre-filled input fields in Angular Material dialogs is not working as expected

I am encountering an issue with a mat-dialog that opens through an edit button within a (mat-)table. Upon opening the dialog, data is passed to populate certain input fields. One of these inputs has validation requiring that it cannot be left empty. The ...

Incorporating a specific time to a JavaScript date object

In my Angular application, I am facing an issue with adding a time to a date. The appointmentDate from the date picker returns a JavaScript date while the appointmentTime is selected from a dropdown with options like "8:00", "8:30", "9:00", etc. I'm ...

Unable to enter PrivateChannel

I have embarked on the journey of setting up a private channel for the first time using Laravel and VueJS. Everything seemed to be going smoothly until I encountered an issue where the event triggers as expected, but I am unable to listen to it in the desi ...

Converting dependencies during Jest test execution

Recently, I introduced tiptap-vuetify as a dependency in my Vue application, triggering the addition of 19 other modules as transitive dependencies. After integrating it, I proceeded to run my tests only to encounter the following error: Jest encountered a ...

The background color of the active tab is updated upon loading the page

I have attempted to modify this code to change the background color of li tag on click. It successfully changes the background color when hovering or clicking, but unfortunately reverts back to the default color upon page refresh. I am looking for a soluti ...

Creating a dynamic layout in a fresh window with jQuery: A step-by-step guide

My goal is to create a dynamic layout using jQuery. The concept involves allowing the user to choose a width and height, which will determine the number of images displayed in rows and columns. The desired outcome is for the user to select a grid size (e. ...

unable to display picture on puggy

Check out the code snippet below: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <title>Home Page</title> </head> <body> <img src="resources/mainlogo.png" style="width:304px;height:2 ...

Difficulty in transmitting two boolean values using ajax and setTimeout()

I am working on two functions that are supposed to send either 0 or 1 to a PHP page using AJAX. When a key is pressed on the keyboard, the function that sends 1 should start, followed by the second function that sends 0 three seconds later using setTimeout ...

Steps for "submitting" a portion of a form with jQuery

I have a form that resembles a spreadsheet layout. My goal is to submit specific fields from a row to the server using jQuery Ajax whenever the user navigates away from that row. The challenge arises because the page consists of one large form, making it n ...

refusing to display the pop-up in a separate window

Hi there, I'm having an issue with a link that's supposed to open in a pop-up but is instead opening in a new tab. I'd like it to open in a proper pop-up window. <button class="button button1" onclick=" window.open('te ...

Node unable to interpret accented characters from CSV file input

Currently, I am utilizing npm fast-csv as my CSV reader/writer tool. It offers a simple and straightforward way to handle CSV files. My goal is to use this tool along with iconv to deal with "accented" characters and non-ASCII characters by converting them ...

Tips for incorporating routes in Polka.js in a way that resembles the functionality of express.Route()

One of the challenges I am facing is trying to import route logic from another file in my project. While using Express.js, this could be done easily with express.Route(). However, when attempting polka.Route(), an error occurs stating that Route doesn&apos ...