Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 254
A-Ota Avatar asked Feb 10 '26 12:02

A-Ota


1 Answers

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

context.expose({ doSomething })
return () => ...
like image 175
Estus Flask Avatar answered Feb 13 '26 02:02

Estus Flask



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!