1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

Organization

Nuxtでmountedが2回呼ばれる

概要

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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?