2021年12月に、匿名で気軽に悩みを相談できる Web アプリ「なやみん」をハッカソンで制作しました。
技術的な挑戦ということで Nuxt 3 を使ってみたので、開発の中で知った主な変更点をメモしてみました。
Installation
Nuxt 2
npx create-nuxt-app <project-name>
Nuxt 3
npx nuxi init <project-name>
Nuxt 2 では対話形式で初期設定をしていたものが、Nuxt 3 ではなくなりました。
必要最低限の構成でインストールされるので、公式のドキュメントを見ながら必要に応じてディレクトリを作る感じです。
TypeScript
Nuxt 3 ではデフォルトが JS ではなく TS になりました。
yarn install した後に yarn build もしくは yarn dev をすると、.nuxt ディレクトリが自動で作成されます。
型定義ファイルや tsconfig.json はここで生成されるので、一度生成しておかないと useStore とかで TS のエラーを吐いちゃいます。
script
Nuxt 2
<script>
export default {
  data: {
    return {
      count: 0
    }
  },
  computed: {
    hoge() {
      return 'fuga'
    }
  },
  mounted() {
    this.count = 1
  }
}
</script>
Nuxt 3
<script setup>
const count = ref(0)
const hoge = computed(() => {
  return 'fuga'
})
onMounted(() => {
  count = 1
})
</script>
Vue 3 で採用されていた Composition API が Nuxt 3 で使えるようになりました。
また、<script setup> が使えるので、コンパクトに書くことができて見やすくなります。
こちらの記事がとても参考になりました。
plugins
Nuxt 2
- 
nuxt.config.jsに記述が必要
Nuxt 3
- 
nuxt.config.tsに記述が不要
- 
/pluginsにファイルを追加するだけで自動でインポートされる
pages
Nuxt 2
-| pages/
---| _id.vue
console.log(this.$route.params)
action() {
  this.$router.push('/hoge')
}
Nuxt 3
-| pages/
---| [id].vue
const route = useRoute()
console.log(route.params)
const router = useRouter()
action() {
  router.push('/hoge')
}
動的ルートのファイル名が変わりました。
フォルダ名にも使えるらしい。
また、route router が useRoute() useRouter() になりました。
Vuex
Nuxt 2
export const state = () => ({
  foo: 'bar'
})
export const getters = {
  getFoo(state) {
    return state.foo
  }
}
<template>
  <div>
    {{ foo }}
  </div>
</template>
<script>
export default {
  computed: {
    foo() {
      return this.$store.getters.getFoo
    }
  }
}
</script>
Nuxt 3
import { useState } from '#app'
export const useFoo = () => {
  return useState('foo', () => 'bar')
}
<script setup>
const foo = useFoo()
</script>
<template>
  <div>
    {{ foo }}
  </div>
</template>
Nuxt 3 で Vuex が廃止されました。
その代わり、/composables にファイルを作り、上記のようにすることでグローバルな値として管理することができます。
便利すぎて感動した。