メインコンテンツまでスキップ

props

props によって、親コンポーネントから子コンポーネントにデータを渡します。 基礎が理解できたら公式を見ることで、さらに理解が深まるかもしれません。

https://ja.vuejs.org/guide/components/props.html

渡すデータの型によって注意するべき点があります。 動的なデータの場合、v-bind またはそのショートカットである : を使うケースに注意しましょう。 https://ja.vuejs.org/guide/components/props.html#static-vs-dynamic-props それぞれの受け渡し方法の例を紹介します。

文字列を渡す

Counter.vue
<script setup>
const props = defineProps(
{
'foo': {
type: String
}
}
)
</script>

<template>
<button>{{ props.foo }}</button>
</template>
App.vue
<script setup>
import Counter from "./Counter.vue"
</script>

<template>
<Counter foo="button" />
</template>

数値を渡す

Counter.vue
<script setup>
import { ref } from 'vue'
const props = defineProps(
{
'count': {
type: Number
}
}
)
const count = ref(props.count)
</script>

<template>
<button @click="count++">{{ count }}</button>
</template>
App.vue
<script setup>
import Counter from "./Counter.vue"
</script>

<template>
<Counter :count="10" />
</template>

その他様々なデータの渡し方

真偽値や配列、オブジェクトなど様々なデータを渡します。授業内で行っていきます。

https://ja.vuejs.org/guide/components/props.html#static-vs-dynamic-props