首页 > 解决方案 > 如何使用 DRF 在 Nuxt.js 中显示动态 url

问题描述

我刚刚得到了关于如何将 DRF 中的信息显示在最后一个线程上的答案。我想知道更多。

我尝试按照基础指南进行操作。但是还是不明白 有没有办法解决这个问题?

我只想做动态页面。https://nuxtjs.org/examples/routing-dynamic-pages

如何让它显示?树路径是

页面

-- _猫名

----产品.vue

索引.vue

_id.vue

抱歉问了很多我真的是初学者

我的 _product.vue

 <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>

和我的 _id.vue

<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>

标签: javascriptvue.jsdjango-rest-frameworknuxt.js

解决方案


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

假设您有上述文件结构。在这种情况下_product.vue,只有 param- product。因此,产品只能被过滤params.product。这是代码。

<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>

推荐阅读