トランジション
Nuxt は transition コンポーネント を使って、ページ間を遷移する際のトランジション/アニメーションを行うことができます。
特定のルートに対してカスタムトランジションを設定するには、ページコンポーネントに transition
キーを追加してください。
export default {
// 文字列を指定できます
transition: ''
// またはオブジェクト
transition: {}
// または関数
transition (to, from) {}
}
文字列
transition
キーに文字列がセットされたときは transition.name
として用いられます。
export default {
transition: 'home'
}
上のように設定すると、Nuxt はコンポーネントに次のようにセットします:
<transition name="home"></transition>
<transition>
コンポーネントを追加する必要はありません。これで、あとはトランジションのための新しいクラスを作るだけです。
<style>
.home-enter-active, .home-leave-active { transition: opacity .5s; }
.home-enter, .home-leave-active { opacity: 0; }
</style>
オブジェクト
transition
キーにオブジェクトがセットされたとき:
export default {
transition: {
name: 'home',
mode: 'out-in'
}
}
上のように設定すると、Nuxt はコンポーネントに次のようにセットします:
<transition name="home" mode="out-in"></transition>
transition
オブジェクトは name、mode、css、duration などの多くのプロパティを持つことができます。詳細は vue のドキュメントを参照してください。
ページ内の transition プロパティで関数を定義することもできます。 詳細は vue のドキュメントの JavaScript フック を参照してください。
export default {
transition: {
afterLeave(el) {
console.log('afterLeave', el)
}
}
}
トランジションモード
transition
モードはデフォルトで out-in
に設定されています。leaving と entering トランジションを同時に実行したい場合、モードプロパティに空文字列をセット(mode: ''
)する必要があります 。export default {
transition: {
name: 'home',
mode: ''
}
}
関数
transition
キーに関数がセットされたとき:
export default {
transition(to, from) {
if (!from) {
return 'slide-left'
}
return +to.query.page < +from.query.page ? 'slide-right' : 'slide-left'
}
}
トランジションは各ページ遷移時に次のように適用されます:
/
から /posts
=> slide-left
に,/posts
から /posts?page=3
=> slide-left
に,/posts?page=3
から /posts?page=2
=> slide-right
に。
グローバルな設定
Nuxt のデフォルトのトランジション名は "page"
です。 アプリケーションのすべてのページでフェードさせるトランジションを追加するには、ルーティング全体に適用されている CSS ファイルが必要です。
assets/main.css
内にグローバルな CSS を書きます:
.page-enter-active,
.page-leave-active {
transition: opacity 0.5s;
}
.page-enter,
.page-leave-to {
opacity: 0;
}
nuxt.config.js
ファイルの css
配列に CSS ファイルのパスを追加します:
export default {
css: ['~/assets/main.css']
}
構成設定
layoutTransition プロパティ
レイアウトトランジションのデフォルト設定を指定するために使われます。
デフォルトの設定は以下の通りです:
{
name: 'layout',
mode: 'out-in'
}
.layout-enter-active,
.layout-leave-active {
transition: opacity 0.5s;
}
.layout-enter,
.layout-leave-active {
opacity: 0;
}
デフォルトの設定を変更したい場合、nuxt.config.js ファイルに以下のように記述してください。
export default {
layoutTransition: 'my-layouts'
// or
layoutTransition: {
name: 'my-layouts',
mode: 'out-in'
}
}
.my-layouts-enter-active,
.my-layouts-leave-active {
transition: opacity 0.5s;
}
.my-layouts-enter,
.my-layouts-leave-active {
opacity: 0;
}
pageTransition プロパティ
デフォルトの設定は以下の通りです:
{
name: 'page',
mode: 'out-in'
}
デフォルトの設定を変更したい場合、nuxt.config.js ファイルに以下のように記述してください。
export default {
pageTransition: 'my-page'
// または
pageTransition: {
name: 'my-page',
mode: 'out-in',
beforeEnter (el) {
console.log('Before enter...');
}
}
}
ページトランジションの名前を変更したい場合、css のクラス名も変更する必要があります。
.my-page-enter-active,
.my-page-leave-active {
transition: opacity 0.5s;
}
.my-page-enter,
.my-page-leave-to {
opacity: 0;
}


















































