LoginSignup
21
14

More than 1 year has passed since last update.

Nuxt 3 で変わったところ

Last updated at Posted at 2021-12-31

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 routeruseRoute() useRouter() になりました。

Vuex

Nuxt 2

store/index.js
export const state = () => ({
  foo: 'bar'
})

export const getters = {
  getFoo(state) {
    return state.foo
  }
}
pages/index.js
<template>
  <div>
    {{ foo }}
  </div>
</template>

<script>
export default {
  computed: {
    foo() {
      return this.$store.getters.getFoo
    }
  }
}
</script>

Nuxt 3

composables/index.ts
import { useState } from '#app'

export const useFoo = () => {
  return useState('foo', () => 'bar')
}
pages/index.js
<script setup>
const foo = useFoo()
</script>

<template>
  <div>
    {{ foo }}
  </div>
</template>

Nuxt 3 で Vuex が廃止されました。
その代わり、/composables にファイルを作り、上記のようにすることでグローバルな値として管理することができます。

便利すぎて感動した。

21
14
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
21
14