How can I retrieve a ref from a child component in Vue.js?

As a beginner to vuejs with limited JavaScript experience, I am using Vue3 in Laravel.

I have a child component that exposes a ref on an input field like so:

<input 
    v-model="raw_input" 
    ref="raw"  
    @input="checkLength(limit)" 
    @keydown="enterNumbers($event)" 
    type="number" 
/>

const raw = ref('');
defineExpose({
    raw
})

In the parent component:

<template lang="">
    <PageComponent title="Dashboard">
    <SmartVolumeInputVue ref="svi" />
    <div class="mt-16 border  h-8">
    {{ val }}
    </div>
    </PageComponent>
</template>

<script setup>
import PageComponent from "../components/PageComponent.vue"
import SmartVolumeInputVue from "../components/customInputs/SmartVolumeInput.vue";import { computed, ref } from "vue";

const svi = ref(null)
//let val=svi
//let val=svi.raw
let val=svi.raw.value
</script>

In the script, there are 3 lines at the bottom, one of which is uncommented at a time: The first line displays this in the template:

{ "raw": "[object HTMLInputElement]" }

The second line displays nothing.

And the third line results in an error:

Uncaught (in promise) TypeError: svi.raw is undefined

I am seeking assistance in retrieving the value of the referenced input in the child component.

Answer №1

Are you looking to reference the element or just retrieve the value?

If not, you can simply display the value like this: Check out a live example

// App.vue
<script setup>
import { ref } from 'vue'
import SmartVolumeInputVue from './SmartVolumeInput.vue'
const svi = ref()
</script>

<template>
    <SmartVolumeInputVue ref="svi" />
  <div>
    {{svi?.raw_input}}
  </div>
</template>
// SmartVolumeInput.vue
<script setup>
import { ref, defineExpose } from 'vue'
const raw_input = ref(123)
defineExpose({
  raw_input
})
</script>

<template>
  <input v-model.number="raw_input" type="number" />
</template>

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

Is there a way to effortlessly upload numerous files in one go when browsing with jquery or JavaScript?

Currently working on a web application and looking to enable multiple file upload functionality within a single browse session, as opposed to selecting one file at a time. The goal is for users to be able to easily select multiple files with just one clic ...

JavaScript - Executing the change event multiple times

Below is the table I am working with: <table class="table invoice-items-table"> <thead> <tr> <th>Item</th> <th>Quantity</th> <th>Price</th> & ...

Looking for assistance with importing OBJ and MTL files into Three.js?

I'm encountering a strange issue while attempting to load an OBJ and MTL file in Three.js using the OBJMTLLoader() function and am unable to find a solution online. My project structure includes an index.html file and a js folder with all the necessar ...

What is the conventional method for sending data by utilizing the output of a previous data submission in Node.js with Express and FaunaDB?

I am in the process of revising a project and have a question about how to post an array of data using the return value of a previous post request as the ID. Here is an overview of the data structure: Checklist A [ChecklistItem 1, ChecklistItem 2, Checkli ...

Error encountered: When attempting to run 'npm run serve' with Vue-i18n, the process fails due to a TypeError that states: "Cannot read property '

Yesterday, my Vue application with i18n was functioning perfectly. However, when I attempted to start it today, I encountered the error displayed in the title. Below is the stack trace: TypeError: Cannot read property 'i18n' of undefined at ...

having difficulty transmitting parameter to angular directive

After assigning a collection to a source variable, I am trying to activate a third party control (bootstrap-select) using a directive that watches the assigned collection. angular .module('app').directive('bootstrapDropdown', ['$t ...

Is it best to remove trailing/leading whitespace from user input before insertion into the database or during the input process?

There's something I've been pondering that pertains to MVC platforms, but could also be relevant to any web-based platform that deals with user input forms. When is the best time and method to eliminate leading/trailing whitespace from user inpu ...

I'm attempting to create a button using html, but I'm puzzled as to why it's not functioning as expected

I've been working on creating a button that, when pressed, generates a new div string based on the node.innerHTML code. For some reason, my code doesn't seem to be functioning properly and I'm not sure why. Here's the HTML: <input ...

Store a collection of objects in an array and assign it to a variable in JavaScript within a React application

Is there a way to loop through this Json data and extract the attribute values into an array for insertion into a constant variable in React? For example: { "data": [ { "id": "1", "type": "vid ...

Troubleshooting why the Angular innerHTML function is failing to render the specified

I'm encountering this problem where I am receiving a string const str = '<p>Please ensure Process Model diagram represents Functions adequately (boxes that represent an activity or group of activities that produce an outcome):</p>< ...

Generating and saving a text file in a React Native application

Is there a way to convert a string into a text file within the client application and then download it directly onto a phone? If so, how can this be achieved? ...

What strategies can I implement to prevent the JavaScript CallStack from becoming overloaded?

The code snippet below outlines the functionality achieved through JavaScript (specifically for a node.js COMET application): A request is sent to the server and held until there is a response. Upon receiving a response, the data is processed, and anothe ...

Troubleshooting: Issue with Firestore & Vue Integration - Retaining Data from Function Wrapper

Within my utility file labeled as "FbUtils.js", I have the following code snippet: getUserById(someUserId) { firebase .firestore() .collection("users") .doc(someUserId) .get() .then((snapshot) => { const res = { userId: someUserId, data: s ...

retrieve profile data asynchronously from the database

I am trying to retrieve data from a database using asyncData and Axios. Below is the code I have been using. However, no request is being sent and I suspect there might be an error in my code. Can someone please assist me in identifying and resolving the ...

Securing my private key on a webpage from potential exposure by mandrillapp

After successfully creating and adding the key in Mandrill, I am able to send emails from my JavaScript page hosted at this link: However, I am facing an issue where my Mandrill key is publicly visible (in the contact_me.js file). I attempted to restrict ...

The issue of deleting the incorrect document ID in React Firebase

I'm currently facing an issue while trying to implement a delete operation on a Firebase database using Reactjs. The problem lies in my function that seems to be fetching the wrong id from Firebase. There's a button triggering the handleOpen fun ...

The subsequent middleware in express next() is failing to trigger the next middleware within the .catch() block

I'm facing a puzzling issue with my POST route. It's responsible for creating transactions through Stripe using the Node package provided by Stripe. Everything works smoothly until an error occurs, such as when a card has insufficient funds. Whe ...

Interactive KML layer in ArcGIS mapping tool

Currently, I am working on enhancing an ArcGIS map by incorporating KML layers for interactivity. This is a simplified version of the code I am currently using: map = new Map("map", { basemap: "topo", center: [-108.663, 42.68], zoom: 6 }); parser.p ...

Having trouble extracting information from JSON object array following an AJAX post?

My website transfers data through JSON objects using Angular's $http post. If you'd like to see the console logs and responses, visit my website: Initially, I used x-form-urlencoded encoding successfully and decided to switch to application/jso ...

HTML form with a dropdown menu

Imagine you have a HTML form containing two dropdown lists. The first dropdown is labeled "country" and contains a list of countries. The second dropdown, labeled "cities," should be dynamically populated based on the country selected. What is the best ...