Home > other >  Vue Composition Api - call child component's method which uses render function
Vue Composition Api - call child component's method which uses render function

Time:11-12

I'm using Vue composition-api with Vue2.
I ran into a problem when I tried to call a method of a component with a render function from its parent.

Without render function, it's ok.

TemplateComponent.vue

<template>
...
</template>
<script lang="ts">
import { defineComponent } from '@vue/composition-api'

export default defineComponent({
  setup (props, context) {
    const doSomething = () => {
      console.log('doSomething')
    }
    return {
      // publish doSomething method.
      doSomething
    }
  }
})
</script>

So, parent component can call TemplateComponent's method like this.

TopPage.vue

<template>
  <TemplateComponent ref="componentRef" />
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from '@vue/composition-api'
import TemplateComponent from '@/components/TemplateComponent.vue'

export default defineComponent({
  components: { TemplateComponent },
  setup (props, context) {
    const componentRef = ref()
    onMounted(() => {
      componentRef.value.doSomething()
    })
  }
})
</script>

With render function, I can't find way to call method.

RenderComponent.vue

<script lang="ts">
import { defineComponent, h } from '@vue/composition-api'

export default defineComponent({
  components: { TemplateComponent  },
  setup (props, context) {
    const doSomething = () => {
      console.log('doSomething')
    }
    // setup method should return render function.
    return () => h('div', 'Hello world!!')
  }
})
</script>

When declare render function with composition api, we should return render function in setup method. https://v3.vuejs.org/guide/composition-api-setup.html#usage-with-render-functions

In this case, I don't understand how to publish doSomething method.
Is there a way to solve this problem?

CodePudding user response:

expose context method exists to combine render function and public instance methods in setup:

context.expose({ doSomething })
return () => ...
  • Related