Nuxtを勉強していて(Vue.jsほとんど触っていない)の基礎なことを備忘録として残します。
随時、更新していきます。
ページの表示
pagesディレクトリに置いたものがページとして表示されます。
また、ファイル名がパスとなります。(ただしindex.vueは例外)
pagesディレクトリに、index.vueがあれば、"/"でページが表示
pagesディレクトリに、about.vueがあれば、"/about"でページが表示
また、ディレクトリをネストすることも可能
pagesディレクトリにshopというディレクトリを作ったとして、
その中にindex.vueとabout.vueを置くと
index.vue⇨"/shop"でページが表示
about.vue⇨"/shop/about"でページが表示
コンポーネント
プロジェクトの直下にcomponentsディレクトリを作り、この中にコンポーネントを作る
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
<template>
<button @click="count++">You clicked me {{ count }} times.</button>
</template>
このCounterコンポーネントをpagesのファイルで使うには、
下記のように書けばいい。Nuxtではcomponentsディレクトリ置いたコンポーネントは
import不要で使える
<script setup lang="ts">
</script>
<template>
<div>
<h1>
Hello, Nuxt
</h1>
<Counter />
</div>
</template>
コンポーネントの値の受け渡し
親コンポーネントから値を受け取るには、definePropsを使う。
definePropsで引数を代入するキーを指定する。(例では'message')
<script setup lang="ts">
const props = defineProps(['message'])
</script>
<template>
<p>{{ props.message }}</p>
</template>
コンポーネントを使用する際に、下記のように値を渡す
<script setup lang="ts">
</script>
<template>
<div>
<h1>
Hello, Nuxt
</h1>
<Counter />
<Post message="こんにちは" />
</div>
</templat>
もし、渡す値が動的に変化する場合(変数など)は以下のように":"をつけて渡す
<Post :message="post.greeting" />