3

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?

2 Answers 2

2

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

context.expose({ doSomething })
return () => ...
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It was documented just below.
0

use

<script setup>
import { ref } from 'vue'

const a = 1
const b = ref(2)

defineExpose({
  a,
  b
})
</script>

https://vuejs.org/api/sfc-script-setup.html#defineexpose

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.