Using Vue Composition API to invoke a child component's method that employs a render function

While using Vue composition-api with Vue2, I encountered an issue when attempting to call a method of a component with a render function from its parent component.

Everything works fine without the render function.

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 {
      // expose doSomething method.
      doSomething
    }
  }
})
</script>

Therefore, the parent component can call the method of TemplateComponent 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>

However, with the render function, I am unable to figure out how to call the 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 declaring a render function with the composition api, it is necessary to return a render function in the setup method. https://v3.vuejs.org/guide/composition-api-setup.html#usage-with-render-functions

In this scenario, I am unsure how to expose the doSomething method. Is there a solution to this issue?

Answer №1

expose method within context allows for the integration of render functions and public instance methods in the setup section:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the significance of utilizing `.value` within a template when working with a function that produces a computed ref?

One of my functions returns a ComputedRef as shown below: // The computed ref function const publishedBooksMessage = () => computed(() => { return books.length > 0 ? 'Yes' : 'No' }) In order to access the value returned by t ...

Vue component always renders a new line

Whenever I include a <component> tag in my main application, it always renders on a new line. Is there a way to make it inline? I am trying to achieve something like this: <p>This is a component :<component></component></p> & ...

The console log is displaying 'undefined' when trying to access Node.js fs

Recently, I was engrossed in developing a Next.js blog. After completing the frontend, I shifted my focus to building the backend using Next.js. ./pages/api I created a new file: ./pages/api/blogs.js To test my backend functionalities, I generated some J ...

An introduction to utilizing .keypress() in jquery

I'm exploring the use of .keypress() to allow users to press enter and trigger a button click on my modal (which closes the modal). When I initially code it as: $(document).keypress(function () { console.log('keypress'); }); it works, but ...

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

A step-by-step guide on creating a unique ticket number sequence in PHP

Looking to create a unique ticket number sequence using PHP? Here's the given sequence: 1-W1 (mandatory). 2-Date (yy-dd-mm) format. 3-001-999 (resets daily from 001). Check out this example: e.g. - W120200101001 I've started the code below, b ...

Loop through an array of arrays in JavaScript. If a match is found, add it to an existing inner array. If not, create a new

I am currently extracting data from a database, and here is a simplified representation of the information: var example = [ {'start': 1966, 'end': 1970}, {'start': 1969, 'end': 1971}, {'start&ap ...

Arranging an Array of Arrays Containing Strings

Looking for a solution to sort an array containing arrays of strings? A similar issue was discussed here. Here is the array in question: var myArray = [ ['blala', 'alfred', '...'], ['jfkdj', ...

Leverage JSON files for pagination in NextJS

I am currently developing a science website where the post URLs are stored in a static JSON file. ScienceTopics.json- [ { "Subject": "Mathematics", "chapters": "mathematics", "contentList": [ ...

Progression from Angular2-rc1 to Angular2-rc2 encounters TypeScript error: anticipating ',' (TS1005)

Encountering an issue with upgrading Angular2 from RC1 to RC2, following exception is being thrown: https://i.sstatic.net/bB6di.png Here's my main.ts file, I haven't made any changes to it during the upgrade process. Line 13 is where the bootstr ...

What could be causing my ASP.Net MVC script bundles to load on every page view?

I'm a bit puzzled. The _layout.cshtml page I have below contains several bundles of .css and .js files. Upon the initial site load, each file in the bundles is processed, which makes sense. However, every time a new view is loaded, each line of code f ...

Working with Variables in Handlebars with Node.js

Is it possible to reference an object key with a space in a handlebars view? The specific key is "Record Number" within the object, but I am encountering difficulties when trying to reference it in the view. Here's the code snippet from the view: {{# ...

What is a creative way to get rid of old content on a webpage using jQuery without relying on the

As I work on my crossword project, I have almost completed it, but encountering a problem. Within my HTML code, I have a select list that loads a .JSON file using Javascript. <form method="post" id="formulaire"> <div class="toto"> <sel ...

Ensuring the accuracy of paths in VueJS

I am working on creating specific routes for different users to ensure each user has a tailored experience. For example, if a user is logged in as an admin, they should be directed to '/admin' instead of '/home'. Here's what I&apos ...

How to eliminate the ng-component tag from an Angular 8 table row template

I currently have a dynamic table component with 2 modes: Normal table - functioning properly Custom Row Template - encountering issues due to Angular adding the <ng-component> tag The logic within the TableComponent is not the main concern, it&apo ...

Using ajax to submit variables may not function properly

I have a set of data that has been processed using JavaScript and I am looking to save it to a database. I have been attempting to code something with AJAX, but so far, I have had no success... What I require: Two variables (id, name) need to be sent to a ...

React.js mouse and touch events do not function properly when on a mobile device's screen

View React, javascript, CSS codes for this issue I encountered some problems with my codepen codes. The code is too long to paste here, so I have included a snippet below. You can view the full code and output screen by clicking on the link below: View O ...

What is the process for transferring an environment.json file to the output directory and then utilizing it with Webpack 4?

Our application is expanding with multiple environments and vendors on the horizon. While the traditional approach of running webpack --env.NODE_ENV=myenvironment works for now, it will soon become inefficient. The main objective here is to streamline the ...

Using TypeScript to consolidate numerous interfaces into a single interface

I am seeking to streamline multiple interfaces into one cohesive interface called Member: interface Person { name?: { firstName?: string; lastName?: string; }; age: number; birthdate?: Date; } interface User { username: string; emai ...

Is Implementing a Promise for Preprocessing in NodeJS Worth It?

Looking to achieve the following using NodeJS + Express: Client sends a post request with JSON document data={text: "I love Stackoverflow", shouldPreprocess: <true or false>}; Need to call an external WebSocket service for sentiment analysis on the ...