【Vue.js 基礎】親 -> 子にpropsとしてfunction(引数)を渡す方法

 

vuejs-title

 
思ったより解決策が思いつかなかったのですが、Vue.jsのissueに一発解決策があったのでここにメモします。
 
# Case「親から子に対してFunctionを渡し、子ではさらに孫に対して渡ってきたFunction(引数)のかたちでPropsを渡したい」
 
 
# Parents.vue
 
 
<template lang="pug">
.parent
 child(
:itemsList="itemsList"
:hogeFunction="onClickHogeHandler"
)
</template>
 
 
<script>
…省略
 data() {
return {
itemsList: [
{text: ‘hoge'},{text: ‘fuga'},{ text: ‘yeah'}
]
}
}
…省略
 methods: {
  onClickHogeHandler(text) {
   console.log(text)
  }
 }
</script>
 
# Child.vue
 
 
<template lang="pug">
.child
 .item-wrapper(v-for=“(item, index) in itemsList” :key=“index")
 grand-child(:on-click=“onClickHogeHandler.bind(this, item.text)")
</template>
 
<script>
…省略
 props: {
  itemsList: {
   type: Array
  },
  onClickHogeHandler: {
   type: Function
  }
 }
</script>
 
# GrandChild.vue
<template lang="pug">
.grand-child
 button(@click=“onClick")
</template>
<script>
…省略
 props: {
  onClick: {
   type: Function
  }
 }
</script>
 
 
解決策の詳細、なぜこうしないといけないのか?は以下のIssueを参照。
おそらくは下位コンポーネントでemitするのが一番綺麗なのかもしれません。一旦動かすならこの方法が一番かんたんです。いまのところ副作用もないです。
 
 
 

f:id:ShowGoTagami:20191104123442p:plain