DEV Community

Koichi Adachi
Koichi Adachi

Posted on

Data passing by props Object and function in OptionsAPI

Definition callback function by PropOptions on Child Component

<template>
  <div>
    <h3>This is a OptionsAPI Component Callback Example</h3>
    <v-btn @click="increment">increment</v-btn>
  </div>
</template>

<script lang="ts">
import { Vue } from 'nuxt-property-decorator'
import { PropOptions } from 'vue'

export default Vue.extend({
  name: 'CallbackChild',
  props: {
    obj: {
      type: Object,
      required: true
    } as PropOptions<{ initialCount: number }>,
    onClickIncrementButtonListener: {
      type: Function,
      required: true
    } as PropOptions<(count: number) => {}>
  },
  data() {
    return { count: this.obj.initialCount }
  },
  methods: {
    increment() {
      this.count++
      this.onClickIncrementButtonListener(this.count)
    }
  }
})
</script>

<style scoped></style>

Call from parent component

passing callback method

<template>
  <div>
    <CallbackChild
      :on-click-increment-button-listener="onClick"
      :obj="{ initialCount: 100 }"
    ></CallbackChild>
    <p v-if="$data.count">{{ count }}</p>
  </div>
</template>

<script lang="ts">
import { Vue } from 'nuxt-property-decorator'
import CallbackChild from '~/components/options/CallbackChild.vue'

export default Vue.extend({
  name: 'CallbackParent',
  components: {
    CallbackChild
  },
  data() {
    return { count: 0 }
  },
  methods: {
    onClick(count: number) {
      this.count = count
    }
  }
})
</script>

<style scoped></style>

Top comments (1)

Collapse
 
adachi_koichi profile image
Koichi Adachi • Edited

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>