如何在 Nuxt2 和 3 的页面中获取路由 url 参数?

How to get route url params in a page in Nuxt2 and 3?

我正在使用 Nuxt.js,并且有一个在

下定义的动态页面
pages/post/_slug.vue

所以,当我访问页面 url 时,比如说 http://localhost:3000/post/hello-world,我如何在我的页面中读取这个 slug 参数值。

目前我正在使用 asyncData 获取它,如下所示:

  asyncData ({ params }) {
    // called every time before loading the component
    return {
      slug: params.slug
    }
  }

这工作正常,但我认为这不是最好的方法,应该有更好的方法使参数对页面可用。任何帮助表示赞赏!

据我所知,这已经是最好的方法,即使不是唯一的方法。但我可以建议一种可能适合您需求的稍微不同的方法。 如果是您的情况,请使用 asyncData 方法从服务器检索数据,而不是将参数放在您的 VM 中并稍后处理。 然后,您可以处理 result 表示逻辑中的数据,而不是任何类型的 request。另一方面,如果您不想将任何内容传递给 VM 或使用 middleware,您也可以使用 fetch,根据满足您的需求。

您可以简单地访问路由参数

供全球使用,但这不是好的做法:

window.$nuxt._route.params

对于 pages/components/layout 等下的本地使用,我们总是应该像下面这样练习

this.$route

this.$nuxt._route.params

在.vue文件中,获取Vue路由器route object:

    this.$route

(注意 Vue routerthis.$router 对象下)

$route 对象有一些有用的属性:

{
  fullpath: string,
  params: {
    [params_name]: string
  },
  //fullpath without query
  path: string
  //all the things after ? in url
  query: {
    [query_name]: string
  }
}

您可以像这样使用 $route 对象:

    <script>
    export default {
      mounted() {
        console.log(this.$route.fullPath);
      }
    };
    </script>

url 路径参数在 route.params 下,如您的情况 route.params.slug

    <script>
    export default {
      mounted() {
        console.log(this.$route.params.slug);
      }
    };
    </script>

Vue mouted hook 仅在客户端运行,当你想在服务器上获取参数时,你可以使用 asyncData 方法:

    <script>
    export default {
        asyncData({route, params}) {
            if (process.server) {
                //use route object
                console.log(route.params.slug)
                //directly use params
                console.log(params.slug)
            }
        }
    };
    </script>

但是,注意:

It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes. ref

如果你不需要服务器端的params信息,比如你不需要根据服务器端的params获取数据,我认为mounted hook就足够了。

如果您想在 apollo 智能查询中访问路线信息:

,其他答案大多就足够了
  apollo: {
    items: {
      query: jobsBy,
      variables() {
        return {
          clientId: this.$route.query.id
        }
      },
    }
  }

如果您在商店上下文中(例如 actions.js),您可以像这样访问查询参数:

this.$router.currentRoute.query['param_name']

要从 URL 读取参数,您应该在 Nuxt 中使用这种方式:

this.$route.query.<name_of_your_parameter_in_url>

例如

URL: https://example.com/example/?token=QWERTYUASDFGH

用这行代码,可以读取token:

this.$route.query.token

然后给你QWERTYUASDFGH.

对我来说最好的方法是:

async asyncData(context){
      const query_params=context.route.query;
}

随着 Nuxt3 稳定版的发布,我想更新一个使用组合 API.

的答案

这就是您在任何 .vue 文件中访问当前路线所有有趣部分的方式

<script setup>
const route = useRoute()
</script>

<template>
  <pre>{{ route }}</pre>
</template>

route 如果要去 http://localhost:5678/about?fruit=watermelon

得到以下信息
{
  "path": "/about",
  "name": "about",
  "params": {},
  "query": {
    "fruit": "watermelon"
  },
  "hash": "",
  "fullPath": "/about?fruit=watermelon",
  "matched": [
    {
      "path": "/about",
      "name": "about",
      "meta": {},
      "props": {
        "default": false
      },
      "children": [],
      "instances": {},
      "leaveGuards": {
        "Set(0)": []
      },
      "updateGuards": {
        "Set(0)": []
      },
      "enterCallbacks": {},
      "components": {
        "default": {
          "__hmrId": "0a606064",
          "__file": "/home/kissu/code/test/n3-default/pages/about.vue"
        }
      }
    }
  ],
  "meta": {}
}

如果你使用 Vue devtools,你也可以点击一个组件并通过控制台找到实例(如果你想快速检查对象很有帮助)。它提供了比 Routes 选项卡更多的详细信息。

此处提供更多信息:https://v3.nuxtjs.org/api/composables/use-route#useroute


使用选项 API,它将是以下内容(如在控制台中)

<script>
export default {
  mounted () {
    console.log('route object', this.$.appContext.app.$nuxt._route.query)
  },
}
</script>

PS: 可能有更短的方法我还不知道。

PS2:我总是混淆 query params"route params",因此 可能会有用。