DEV Community

Discussion on: Data passing by props Object and function in OptionsAPI

Collapse
adachi_koichi profile image
Koichi Adachi Author • Edited on

Pattern2
Object(include callback function) instead of Function
like a android app callback structure

CallbackChild.vue

<template>
    <v-btn @click="increment">increment</v-btn>
</template>
<script lang="ts">
interface OnClickListener {
  onClick(count: number): (count: number) => {}
}
export default Vue.extend({
  props: {
    onClickListener: {
      type: Object,
      required: true
    } as PropOptions<OnClickListener>
  },
  data() {
    return { count: this.obj.initialCount }
  },
  methods: {
    increment() {
      this.count++
      this.onClickListener.onClick(this.count)
    }
  }
}
</script>

CallbackParent.vue

<template>
    <CallbackChild
      :on-click-listener="$data.onClickListener"
    ></CallbackChild>
</template>
<script lang="ts">
export default Vue.extend({
  data() {
    const onClickListener = {
      onClick: (count: number) => {
        console.log(`onClickListener.onClick(${count})`)
      }
    }
    return { onClickListener }
  },
}
</script>