📓

Vue.jsの練習③(公式チュートリアルstep-11~step-14)

2024/05/07に公開

Vue.jsの練習②の続き
https://zenn.dev/matcha22/articles/380db2718e4362

https://vuejs.org/tutorial/
step-11から最後まで
今回は、親子コンポーネント間の移行に関する内容中心

step-11 コンポーネント

子コンポーネントの引用
Scriptタグ内に挿入

import ChildComp from './ChildComp.js'

createApp({
  components: {
    ChildComp
  }
})

templateタグ内に挿入

<child-comp></child-comp>
index.js
<script type="module">
import { createApp } from 'vue'
import ChildComp from './ChildComp.js'

createApp({
  components: {
    ChildComp
  }
}).mount('#app')
</script>

<div id="app">
  <child-comp></child-comp>
</div>
ChildComp.js
export default {
  template: `
  <h2>A Child Component!</h2>
  `
}

step-12 props

子コンポーネントは、props を介して親コンポーネントからの入力を受取り可能。
V-bind等を用いることにより、動的な値を渡すことも可能である。

<child-comp :msg="greeting"></child-comp>

その際、propsの宣言が必要。ただし、defineProps()はコンパイル時マクロのため、importは不要

// in child component
export default {
  props: {
    msg: String
  }
}

子コンポーネント

childcomp.vue
export default {
  props: {
    msg: String
  },
  template: `
  <h2>{{ msg || 'No props passed yet' }}</h2>
  `
}

親コンポーネント

index.vue
<script type="module">
import { createApp } from 'vue'
import ChildComp from './ChildComp.js'

createApp({
  components: {
    ChildComp
  },
  data() {
    return {
      greeting: 'Hello from parent'
    }
  }
}).mount('#app')
</script>

<div id="app">
  <child-comp :msg="greeting"></child-comp>
</div>

step-13 Emits

propsとは逆に子コンポーネント側から親コンポーネントにイベントを発行する際に使用

export default {
  emits: ['response'],
  created() {
    this.$emit('response', 'hello from child')
  }
}

使用例

index.html
<script type="module">
import { createApp } from 'vue'
import ChildComp from './ChildComp.js'

createApp({
  components: {
    ChildComp
  },
  data() {
    return {
      childMsg: 'No child msg yet'
    }
  }
}).mount('#app')
</script>

<div id="app">
  <child-comp></child-comp>
  <p>{{ childMsg }}</p>
</div>
childcomp.js
export default {
  emits: ['response'],
  created() {
    this.$emit('response', 'hello from child')
  },
  template: `
  <h2>Child component</h2>
  `
}

step-14 スロット

スロット機能を使うことで、親コンポーネントはプロパティを介してデータを渡すことに加えてテンプレートフラグメントを子に渡すことも可能

index.html
<script type="module">
import { createApp } from 'vue'
import ChildComp from './ChildComp.js'

createApp({
  components: {
    ChildComp
  },
  data() {
    return {
      msg: 'from parent'
    }
  }
}).mount('#app')
</script>

<div id="app">
  <child-comp>Message: {{ msg }}</child-comp>
</div>
ChildComp.js
export default {
  template: `
  <slot>Fallback content</slot>
  `

一言感想

step-15は特に意味ない章の為、省略する。
コンポーネントについては今までの内容に比べて難しい。
まだ理解できたか怪しいので、最初の予定通りComposition & SFCでもう一周しながら理解を深めていくことにする。

Discussion