Leveraging Vue.js and TypeScript: accessing the type of the child component through refs

In my parent component, I have a child component named with a reference passed to it:

<child
  ref="childRef"
/>

When trying to execute a function inside the child component from the parent component, I face some challenges:

mounted() {
  (this.$refs.childRef as any).testFunction();
}

The above code works without specifying a type, but how can I set the correct type for running this function?

If I try to specify the type of the child component like this:

(this.$refs.childRef as Child).testFunction();

I still get an error saying that property testFunction does not exist on type 'Vue'.

I am using Vue.js version 2.

This is the code for my child component:

@Component({})
export default class Child extends Mixins(CustomMixin) {
  testFunction() {
    console.log('test');
  }
}

Update: I also came across this solution to call the function successfully:

(this.$refs.childRef as Child & { testFunction:() => void }).testFunction();

This updates the Child type with the method testFunction() and it works. However, I am unsure if this is the best approach.

Answer №1

It seems like your code is in good shape, and it should work fine as the ref within the child component holds the Child component instance. Below is a snippet of the code for you to review and compare with your own code to identify any potential issues.

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <child ref="childComponent"></child>
</div>

Vue.component('child', {
    methods: {
    testFunction() {
        console.log('test function call')
    }
  }
});

var app = new Vue({
  el: '#app',
  mounted() {
    (this.$refs.childComponent as Child).testFunction();
  }
});

Here's the link to the demo for reference: https://jsfiddle.net/w6bjso78/

Answer №2

The solution I've come up with is:

(this.$refs.childRef as Child & { testFunction:() => void }).testFunction();

It seems to work, but I'm not sure if this is the most ideal approach. This code updates the Child type with a method testFunction that returns void.

Answer №3

Here's how I tackled the issue:

const MyComponent = ref<InstanceType<typeof MyFileBoard>>()

If you want more information, check out this link.

Answer №4

My preferred approach involves using setup with the lang attribute set to "ts"

In my opinion, the optimal method is as follows:

// child-component.vue

export interface IEtapa {
  fetchEnviosContar(): Promise<void>
}

const fetchEnviosContar = async ():Promise<void>=>{
  console.log("hello world")
})
defineExpose<IEtapa>({
  fetchEnviosContar,
})

// parent-component.vue

import Etapas, { IEtapa } from '../components/etapas/index.vue'

const refEtapasComponent = ref<IEtapa | null>(null)

refEtapasComponent.value?.fetchEnviosContar()

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

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

IntelliJ IDEA does not support the recognition of HTML tags and directives

I seem to have lost the ability to switch between my HTML and TS files in Intellij IDEA; the tags, directives, and autocompletion in HTML are no longer working. Additionally, I'm receiving some warnings: https://i.stack.imgur.com/QjmNk.png Is there ...

When viewing a React data table in Chromium browsers, the columns on the right side may flicker when the screen is small or the browser

I recently integrated the React data grid Npm package by adazzle. You can find more information about it here. I encountered an issue which you can see in this example: https://codesandbox.io/s/react-data-grid-example-9sb93?file=/src/App.tsx When using a ...

calculate the difference between two dates and then add this difference to a new date

Utilizing TypeScript for date calculations. Example: Initial Date 1: "10/06/2021 10:10:05" Initial Date 2: "08/06/2021 11:10:05" Calculate the difference between the two dates, including date/month/year/hour/min/sec/milliseconds. Ensure compatibility wi ...

The specified property 'XYZ' is not found in the type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

Whenever I try to access .props in RecipeList.js and Recipe.js, a syntax error occurs. Below is the code snippet for Recipe.js: import React, {Component} from 'react'; import "./Recipe.css"; class Recipe extends Component { // pr ...

Clicking on a Vue.js element does not trigger the function when an <a> link is present

I am attempting to create a notification system where clicking on the notification and accessing its link will result in a decrease in the total number of notifications.<li class="header">You have {{ notificationsCount() }} notifications</li> & ...

node.js + typescript How can we access instances from methods?

Following a server rebuild, the compiler creates an instance in the included API controller as shown below: NewController.ts import express = require("express"); import INew = require("../interface/INew"); import New ...

Using Angular and Typescript to implement mathematical formulas involving date object subtraction

I need help converting the following Excel formula to Typescript. I keep running into an error that says 'The left-hand and right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type'. Can anyon ...

Instructions on activating dark mode with the darkreader plugin on a Vue.js website

Is there a way to implement DarkMode in a Vue.js application? I attempted to integrate darkmode using this npm package, but I kept encountering the error message: DarkMode not defined. ...

Is there any advice for resolving the issue "In order to execute the serve command, you must be in an Angular project, but the project definition cannot be located"?

Are there any suggestions for resolving the error message "The serve command requires to be run in an Angular project, but a project definition could not be found."? PS C:\angular\pro\toitsu-view> ng serve The serve command requires to be ...

Which type of comparator does Vuetify utilize for sorting string columns in a data table?

If I modify the standard Vuetify example to have Calorie values as Strings instead of numbers, and now the data is not entirely numeric: https://codepen.io/hobbeschild/pen/WNQWmrJ What sorting method does Vuetify use internally for ordering these Strings? ...

Tips for displaying real-time data and potentially selecting alternative options from the dropdown menu

Is there a way to display the currently selected option from a dropdown list, and then have the rest of the options appear when the list is expanded? Currently, my dropdown list only shows the available elements that I can choose from. HTML: < ...

Is there a way to transform time into a percentage with the help of the moment

I am looking to convert a specific time range into a percentage, but I'm unsure if moment.js is capable of handling this task. For example: let start = 08:00:00 // until let end = 09:00:00 In theory, this equates to 100%, however, my frontend data ...

Changing an Angular template.html into a PDF document within an Angular 2 application can be achieved by utilizing

Exploring Angular 2 and looking for a way to export my HTML component in Angular 2 to PDF using jspdf. I want to convert dynamically generated tabular HTML into a PDF using jspdf. Below is a snippet of sample code along with a Plunker link: import {Comp ...

Creating a table with merged (colspan or rowspan) cells in HTML

Looking for assistance in creating an HTML table with a specific structure. Any help is appreciated! Thank you! https://i.stack.imgur.com/GVfhs.png Edit : [[Added the headers to table]].We need to develop this table within an Angular 9 application using T ...

There is no defined method "response" in the IlluminateViewView class

I am encountering an issue while attempting to retrieve data from a table. Here is my controller : public function admin() { $users = User::with('subs')->get(); return view('admin')->response()->json([ 'us ...

Create visual representations using the data displayed in charts generated by Chart JS

Good evening. I am currently utilizing Chart JS in my project to visualize the total count per column in a bar graph. My backend framework is Laravel, and I pass the data from the controller using the variable $datacount. This snippet shows the query in ...

What is the best way to avoid passing a value to a component in nextjs?

I'm trying to make this component static and reusable across different pages without passing a parameter when calling it. Is there a way to achieve this while following the official documentation? component: import { GetStaticProps, InferGetServerSid ...

The router's handler function sends back a collection of objects, but for some reason, the client is not receiving them in JSON format even though the response

I am currently developing an Express.js project using Typescript. In my project, I have defined an enum and an interface as follows: export enum ProductCategory { ELECTRONICS = 'electronics', CLOTHING = 'clothing', TOYS = & ...

Send two field values via axios by utilizing a b-form-select component from the Bootstrap Vue library

I'm struggling to send two fields to my backend, but every time I attempt to do so, both values end up as null in the backend. I am uncertain about what mistake I might be making. <template> <div id="app"> <div> ...