9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt.jsで現在のurlを取得する方法

Last updated at Posted at 2021-07-08

Nuxt.jsで現在のurlを取得する方法になります。

https://demosaite.com/demo/2?user=123

本記事では、上記のurlを例に解説しています。

基本的には、Vue Routerを使用することで取得できます。

template内で現在のurlを取得する

<template>
  <div>
    <p>{{ $route.fullPath }}</p> <!-- /demo/2?user=123 -->
    <p>{{ $route.name }}</p> <!-- demo-id -->
    <p>{{ $route.params }}</p> <!-- { "id": "2" } -->
    <p>{{ $route.path }}</p> <!-- /demo/2 -->
    <p>{{ $route.query.user }}</p> <!-- 123 -->
  </div>
</template>

template内では、$routeで現在のurlを取得することができます。

コンポーネントプロパティで現在のurlを取得する

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  mounted() {
    console.log(this.$route.params) // { "id": "2" }
    console.log(this.$route.query.user) // 123
  }
})
</script>

mountedなどのコンポーネントプロパティからは、thisをつけることで現在のurlを取得できます。

Nuxtのコンテキストでurlのクエリパラメータを取得する

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  asyncData({ route }) {
    console.log(route.path) // /demo/2
    console.log(route.name) // demo-id
  }
})
</script>

asyncDatamiddlewareなどのNuxtのコンテキストからは、上記のようにurlを取得できます。

httpsなどを含む全てのurlを取得したい場合

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  mounted() {
    console.log(window.location.href)
    // https://demosaite.com/demo/2?user=123
  }
})
</script>

httpsなどを含む全てのurlを取得したい場合は、window.location.hrefを使うことで取得できます。

9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?