Retrieving the input value using ref in Vue 3 and TypeScript

It appears to be a straightforward issue, but I haven't been able to find consistent Vue 3 TypeScript documentation on accessing an input field and retrieving its value from within a function.

<template>
  <Field
    type="text"
    name="test"
    ref="input"
  />

  <span @click="testFunc()">Test</span>
</template>

export default defineComponent({
...
setup() {
  const input = ref<HTMLInputElement | null>(null);

  const testFunc = () => {
    if (input.value) {
       console.log(input.value.value); // always undefined
    }
  };

  return {
   input,
   testFunc,
  }
});

Note: I'm very new to Vue and TypeScript, so please be patient with me :)

Answer №1

One solution is to utilize the v-model binding.

<template>
  <Field
    type="text"
    name="test"
    v-model="input"
  />
</template>

If you want to execute a function upon change, consider using watch(). Import watch from 'vue'.

watch(input, (newValue, oldValue)=>{
   console.log(newValue, oldValue)
})

I hope this solution proves helpful.

By the way, slightly off-topic (but useful if you are new to Vue), you can also leverage <script setup>, which simplifies the setup process. Review the documentation for more details.

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

React Date-Picker is unable to process a date input

Recently, I've been working on integrating a date picker into my application. I came across this helpful library that provides a date picker component: https://www.npmjs.com/package/react-date-picker So far, I have set up the component in the follow ...

Determining changes in an object with Angular 2 and Ionic 2

Q) How can I detect changes in an object with multiple properties bound to form fields without adding blur events to each individual field? I want to avoid cluttering the page with too many event listeners, especially since it's already heavy. For e ...

Loading a view in Ionic2 with Angular2 after a successful subscription

After completing an http post request, I want to navigate to the next view in my app. Here is a breakdown of the three services I am using: The server service handles generic http calls such as get and post requests. The city service stores a list of ...

Tips for maintaining the currentPage variable in Vue when navigating through detail links

As I delve into vue.js, the code snippet below seems to be working smoothly. The concept is quite simple - when a user clicks on the detail, they are directed to another component to view more information about the user. However, what I am struggling with ...

specialized registration process with auth0 in Angular

I am attempting to enhance the user information in a single call. The process involves first signing up with a username and password on Auth0, followed by adding additional userinfo to the database during the callback phase. However, I am encountering diff ...

Tips for preserving @typedef during the TypeScript to JavaScript transpilation process

I have a block of TypeScript code as shown below: /** * @typedef Foo * @type {Object} * @property {string} id */ type Foo = { id: string } /** * bar * @returns {Foo} */ function bar(): Foo { const foo:Foo = {id: 'foo'} return f ...

The geolocation feature is operational in the browser test, but it is not functioning properly on the

I am currently creating an application that requires accessing the user's location at a specific point in time. To achieve this, I have utilized the ionic native geolocation feature which communicates with the Google API for reverse geocoding. Everyt ...

Accessing JSON data stored locally and initializing it into a TypeScript variable within a React application

I'm new to working with JSON arrays and I'm facing a challenge. I am looking for a way to load data from a JSON file into a Typescript variable so that I can perform a specific operation that involves arrays. However, I'm unsure of how to ac ...

An issue has occurred when attempting to import ES Module for setting all values to an object

Working on a project in Angular 6, I encountered an issue with using the npm package object-set-all-values-to version 3.9.45. Here's what I did: 1- Successfully installed it using npm i object-set-all-values-to ✔️ OK 2- However, when trying to i ...

Guide to Removing Nuxt Modules and Packages

Currently using Nuxt 2.13 and looking to remove some packages from my project. In the past, I simply deleted them from the package.json file and ran npm i to uninstall the package. However, now I am encountering an error: Module @nuxtjs/google-gtag not fou ...

Having trouble with errors when adding onClick prop conditionally in React and TypeScript

I need to dynamically add an onClick function to my TypeScript React component conditionally: <div onClick={(!disabled && onClick) ?? undefined}>{children}</div> However, I encounter the following error message: Type 'false | (() ...

tips for optimizing javascript file caching

https://i.stack.imgur.com/UhWD1.pngMy web application was created using "pug" technology about 9-8 years ago, and more recently, pages have been added in an innovative framework (vue.js). However, whenever there is a transition between an old pug page and ...

Angular: Discover the best way to delegate translation tasks to your S3 bucket!

I am currently using ngx-translate for handling translations in my Angular application. Everything is functioning properly when the translation files are stored within the app itself. However, I want to move all of my JSON translation files to an AWS S3 bu ...

The spread operator seems to be malfunctioning whenever I incorporate tailwindcss into my code

Hi there! I hope you're doing well! I've come across a strange issue in Tailwindcss. When I close the scope of a component and try to use props like ...rest, the className doesn't function as expected. Here's an example: import { Butto ...

Define an object by extracting properties from an array of objects

Is there a way to refactor this code to remove the need for explicit casting? type A={a:number}; type B={b:string}; let a:A={a:0}; let b:B={b:''}; function arrayToObject<T>(array:T[]):T { return array.reduce((r,c) =>Object.assign ...

What is the purpose of exporting both a class and a namespace under the same name?

While exploring some code, I came across a situation where a class and a namespace with identical names were exported from a module. It seems like the person who wrote this code knew what they were doing, but it raised some questions for me. Could you shed ...

How come the path alias I defined is not being recognized?

Summary: I am encountering error TS2307 while trying to import a file using an alias path configured in tsconfig.json, despite believing the path is correct. The structure of directories in my Angular/nx/TypeScript project appears as follows: project |- ...

What could be the source of the error message: "Error: .eslintrc.js: The environment key 'vue/setup-compiler-macros' is not recognized

I am currently working on a sample application using Vue 3 and Typescript. Specifically, I have opted for the new Vue v3.2 setup option within the section of the Vue SFC. Following the guidance from the Vue documentation, I included "vue/setup-compiler-ma ...

Utilizing the `filterBy` function with a custom select list that changes dynamically

I'm currently in the process of constructing a form with an extensive selection of drop-down items utilizing vue.js. My approach involves implementing the dynamic select list as detailed in this documentation: However, I am interested in providing us ...

What are some methods to manage the timing of sending socket connection requests from the client to the backend server?

Currently using vue-socket.io, my frontend initiates a Socket.io connection request to the backend when the app is first being built or whenever the page is refreshed. This poses an issue for me because the page is initially constructed on the landing page ...