LoginSignup
0
0

Vue Props Example

Last updated at Posted at 2024-01-20

Propsとは何か

親コンポーネントから子コンポーネントを呼び出す際に、子コンポーネントに情報を受け渡しす仕組み
コンポーネント分割をするために習得必須

ChildComponent.vue
<script setup lang='ts'>
const props = withDefaults(defineProps<{
  // 型定義
  user_id: string,
  message: string
}>(), {
  // 初期値設定
  message:''
});
</script>

<template>
<h1>メッセージ確認</h1>
title: {{ props.user_id }}<br>
message: {{ props.message }}
</template>

ParentComponent.vue
<script setup lang='ts'>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'

let userId = ref('');
let Message = ref('');
</script>

<template>
<div>
<h1>メッセージ入力</h1>
<v-input label='user_id' v-model='user_id"></v-input>
<v-input label='message' v-model='message"></v-input>
<!-- 子コンポーネントの呼び出し 呼び出し時にPropsでデータを渡す -->
<ChildComponent :user_id='userId' :message='Message'>
</div>
</template>

学び始めに躓いたとこと

  • childrenコンポーネントにおけるprops定義の記述方法について、検索するとVue2系におけるOptions APIの書き方がたくさん出てくる Composition APIの書き方がわからず困った。
  • ":user_id=" のように:を付けるのはscriptに記載している変数を参照するためにつける。つけなければ単なる文字列として扱われる。

参照情報

0
0
1

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
0
0