LoginSignup
2
1

More than 3 years have passed since last update.

Nuxtでmountedが2回呼ばれる

Posted at

概要

mountedが2回発火して初期化処理が狂うことがありました
レアケースだと思うけどめっちゃハマったので残しときます

対策

nuxtのバージョンを上げましょう
v2.14.1とかv2.14.6なら大丈夫でした

コード的には問題なくて多分nuxt側のバグ

現象再現

以下条件を満たせば発生した

  • nuxtのバージョンがv2.12.2
  • ページ遷移前後でレイアウトが違う
  • transitionでmode: 'in-out'が指定されている

index.vue

<template>
  <div>
    <div>
      <button @click="toNextPage">button</button>
    </div>
  </div>
</template>

<script>
export default {
  layout: 'test_layout',
  methods: {
    toNextPage() {
      this.$router.push('/sample')
    },
  },
  transition: { name: 'page', mode: 'in-out' },
}
</script>

sample.vue

<template>
  <div>
    <div>
      <nuxt-link to="/">back</nuxt-link>
    </div>
  </div>
</template>

<script>
export default {
  asyncData() {
    console.log('asyncData')
  },
  fetch() {
    console.log('fetch')
  },
  data() {
    console.log('data')
    return {}
  },
  created() {
    console.log('created')
  },
  mounted() {
    console.log('mounted')
  },
  beforeDestroy() {
    console.log('beforeDestroy')
  },
  destroyed() {
    console.log('destroyed')
  },
}
</script>

indexからsampleへのページ遷移時のログ

mountedどころか破棄されてもう一回作られてますね
でもasyncDataは1回

asyncData
data
created
fetch
mounted
beforeDestroy
destroyed
data
created
fetch
mounted
2
1
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
2
1