コンテキストとヘルパー
コンテキストは、アプリケーションへの現在のリクエスト (request) に関する追加の情報とオプション情報を提供します。
context
オブジェクトは、asyncData 、plugins 、middleware そして nuxtServerInit といった特定の Nuxt 関数で利用できます。これは、アプリケーションへの現在のリクエストに関する追加の情報とオプション情報を提供します。
何よりもまず、コンテキストは Nuxt アプリケーションの他の部分(例えば Vuex ストアや基盤となる connect
インスタンス)へのアクセスを提供するために使用されます。そのため、サーバーサイドと store
で使用可能なコンテキストの req
オブジェクトと res
オブジェクトは常に使用可能です。しかし、時間が経つにつれコンテキストは他の多くの役立つ変数やショートカットで拡張されました。今では development
モードの HMR (ホットモジュールリロード、またはリプレイスメント) 機能、現在の route
、ページの params
、そして query
にアクセスできるほか、コンテキストを介して環境変数にアクセスするオプションもあります。さらに、モジュール関数とヘルパーは、クライアントサイドとサーバーサイドの両方で使用できるようにコンテキストを通じて公開できます。
デフォルトで存在するすべてのコンテキストキー
function (context) { // asyncData, nuxtServerInit, ...
// 常に利用可能
const {
app,
store,
route,
params,
query,
env,
isDev,
isHMR,
redirect,
error,
$config
} = context
// サーバーサイドでのみ利用可能
if (process.server) {
const { req, res, beforeNuxtRender } = context
}
// クライアントサイドでのみ利用可能
if (process.client) {
const { from, nuxtState } = context
}
}
context
オブジェクトや nuxt.config.js
の build.extend
関数で利用可能な context
オブジェクトと混同しないでください。これらは互いに関連していません!他のコンテキストキーについての詳細はコンテキストのドキュメント を参照してください。
API クエリ用にページパラメータを使う
コンテキストは context.params
を介してルートのとりうる動的パラメータを直接公開します。次の例では、URL の一部として動的ページパラメータを使用して、nuxt/http
モジュールを介して API を呼び出します。nuxt/http モジュールは、context.app オブジェクトを介して利用できる独自の関数を公開できます。
また、潜在的なエラーを処理するために API の呼び出しを try/catch
構文でラップします。context.error
関数を使用すると、Nuxt のエラーページを直接表示して発生したエラーを渡すことができます。
export default {
async asyncData(context) {
const id = context.params.id
try {
// nuxtjs/http モジュールをここで使い context.app を介して公開します
const post = await context.app.$http.$get(
`https://api.nuxtjs.dev/posts/${id}`
)
return { post }
} catch (e) {
context.error(e) // スローしたエラーと一緒に nuxt エラーページを表示します
}
}
}
ES6 を使用すると、この構文を使用してコンテキストオブジェクトを分解できます。アクセスしたいオブジェクトを渡すと、コンテキストという単語を使用せずにコードでそれらを使用できます。
export default {
async asyncData({ params, $http, error }) {
const id = params.id
try {
// nuxtjs/http モジュールをここで使い context.app を介して公開します
const post = await $http.$get(`https://api.nuxtjs.dev/posts/${id}`)
return { post }
} catch (e) {
error(e) // スローしたエラーと一緒に nuxt エラーページを表示します
}
}
}
代わりにクエリパラメータを使いたい場合は、context.query.id を使ってください。
ユーザをリダイレクトさせストアへアクセスする
Vuex store ストアへのアクセス(store
ディレクトリを介して設定した場合)もコンテキストを介して可能です。これは、Vue コンポーネントで this.$store
として扱うことができる store
オブジェクトを提供します。さらに、コンテキストを介して公開されたヘルパーである redirect
メソッドを使用して authenticated
状態が falsy な場合にユーザーをリダイレクトします。
export default {
middleware({ store, redirect }) {
// 分解した (destructuring) オブジェクトからキーを取得する
const isAuthenticated = store.state.authenticated
if (!isAuthenticated) {
return redirect('/login')
}
}
}
ヘルパー
コンテキスト内のショートカットに加えて、Nuxt アプリケーションには他の小さなヘルパーもあります。
$nuxt
: Nuxt ヘルパー
$nuxt
はユーザーエクスペリエンスを向上させ、状況によってはエスケープハッチになるように設計されたヘルパーです。Vue コンポーネントでは this.$nuxt
を介してアクセスでき、それ以外の場合はクライアント側で window.$nuxt
を介してアクセスできます。
コネクションチェッカー
$nuxt
ヘルパーはユーザーのインターネット接続があるかどうかをすばやく確認する方法を提供します。ブール値の isOffline
と isOnline
を公開します。これらを使用して例えば、ユーザーがオフラインになるとすぐにメッセージを表示できます。(以下の例)
<template>
<div>
<div v-if="$nuxt.isOffline">You are offline</div>
<Nuxt />
</div>
</template>
ルートインスタンスへアクセスする
DX/UX (デベロッパーエクスペリエンス / ユーザーエクスペリエンス) 機能を提供することに加え、$nuxt
ヘルパーは他のすべてのコンポーネントからアプリケーションのルートインスタンスへのショートカットも提供します。しかし、それだけではありません。Vue コンポーネントの外部から $axios
などのモジュールメソッドにアクセスするためのエスケープハッチとして使用できる window.$nuxt
を介して $nuxt
ヘルパーにアクセスすることもできます。賢明に使う必要があり最後の手段としてしてください。
ページデータのリフレッシュ
ユーザーの現在のページを更新したい場合、サーバーに再度アクセスして少なくとも Nuxt アプリケーション全体を再初期化する可能性があるのでページを完全にリロードさせたくないでしょう。リロードの代わりに asyncData
または fetch
によって提供されるデータのみを更新したい場合がよくあります。
これは this.$nuxt.refresh()
を使って行えます!
<template>
<div>
<div>{{ content }}</div>
<button @click="refresh">Refresh</button>
</div>
</template>
<script>
export default {
asyncData() {
return { content: 'Created at: ' + new Date() }
},
methods: {
refresh() {
this.$nuxt.refresh()
}
}
}
</script>
ローディングバーの制御
$nuxt
を使うと、Nuxt のローディングバーを this.$nuxt.$loading
を介してプログラムで制御できます。
export default {
mounted() {
this.$nextTick(() => {
this.$nuxt.$loading.start()
setTimeout(() => this.$nuxt.$loading.finish(), 500)
})
}
}
詳細についてはローディング機能のドキュメント を参照してください。
onNuxtReady ヘルパー
Nuxt アプリケーションがロードされて準備ができた 後 、いくつかのスクリプトを実行する場合は、 window.onNuxtReady
関数を使用できます。これはサイトのインタラクティブ化にかかる時間を増やすことなく、クライアントサイドで関数を実行したい場合に便利です。
window.onNuxtReady(() => {
console.log('Nuxt is ready and mounted')
})
プロセスヘルパー
Nuxt はグローバルな process
オブジェクトに 3 つのブール値 (client
、 server
および static
) を挿入します。これはアプリケーションがサーバーでレンダリングされたか、完全にクライアントでレンダリングされたかを判断し、静的サイトの生成を確認するのに便利です。これらのヘルパーはアプリケーション全体で利用でき、asyncData
ユーザーランドコードで一般的に使用されています。
<template>
<h1>I am rendered on the {{ renderedOn }} side</h1>
</template>
<script>
export default {
asyncData() {
return { renderedOn: process.client ? 'client' : 'server' }
}
}
</script>
この例ではサーバーサイドレンダリングを使用し、ユーザーが直接ページにアクセスすると renderedOn
は 'server'
と評価されます。ユーザーがアプリケーションの別の部分からページに遷移する場合(例えば <NuxtLink>
をクリックする場合)クライアントに評価されます。












































