如何在 Nuxt.js 中传递动态参数?

阅读 1k
avatarAI BotBETA

首先,您需要确保您正在尝试传递的参数是全局可访问的。这意味着它们需要在您的组件之外定义,例如在 Vuex store 中,或者作为全局变量。

然后,您可以通过将参数传递给 Nuxt.js 的路由生成器来传递动态参数。这可以通过在您的 nuxt.config.js 文件中的路由定义中添加动态参数来实现。

例如,假设您有一个名为 product 的页面组件,并且您希望将动态参数传递给它。您可以按照以下方式定义路由:

export default {
  router: {
    routes: [
      {
        path: '/product/:appId',
        name: 'product',
        component: () => import('../pages/Product.vue')
      }
    ]
  }
}

在这里,:appId 是一个动态参数,它可以匹配任何字符串。当您访问 /product/1/product/2/product/3 时,Nuxt.js 将渲染 Product.vue 组件,并将匹配到的 URL 参数作为 $route.params.appId 传递给该组件。

然后,在您的 Product.vue 组件中,您可以通过 this.$route.params.appId 来访问这个参数。

请注意,Nuxt.js 默认不会将 URL 参数作为 props 传递给 Vue 组件。因此,您需要在您的组件中手动获取这些参数。另外,由于 this.$route.params 在页面渲染后不再更新,因此您不应该在 mounted()created() 生命周期钩子中使用它,因为这些钩子在页面渲染后立即执行。相反,您应该在模板或计算属性中使用它。

2 个回答

不知道你要干嘛,难道不是 /product/app/[id].vue 么?

App.vue 应该是这样的

<script setup lang="ts">
const list = ref([
    {
        id: 1,
        title: 'AAAAAA'
    },
    {
        id: 2,
        title: 'BBBBB'
    },
    {
        id: 3,
        title: 'cccc'
    }
])
</script>

<template>
<div class="container">
    <h1>免费 App</h1>
    <div class="row">
        <NuxtLink v-for="(item, index) in list" :key="index" :to="'/product/app/' + item.id">{{item.title}}</NuxtLink>
    </div>
</div>
</template>

<style scoped>

</style>

[id].vue

<script setup lang="ts">
const route = useRoute();

console.log(route.params.id)
</script>

<template>
<div class="container">
    <h1>{{route.params.id}}</h1>
</div>
</template>

<style scoped>

</style>

这能看明白不


[id].vue 页面是要根据这个 route.params.id 去请求后台JSON数据,下面随便一个例子

const { data } = await useFetch('/api/product/' + route.params.id);

官方文档:https://nuxt.com/docs/getting-started/data-fetching

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题