Trouble accessing a method from a ref in Vue 3 Typescript

Hey everyone, I'm a newcomer to Vue 3 and Typescript and currently facing a challenge with resolving a typescript error in my project. The error I'm encountering is related to the 'validate' method not being found, even though it shows up when I try to console log it.

The issue states: Property 'validate' does not exist on type 'string'.

https://i.sstatic.net/yu8u2.png

In my project, I am utilizing Vue 3 composition API along with Typescript and Vue Element Plus. Below is an excerpt from my component code for reference:

Component

    <template>
  <div class="w-full h-full absolute flex">
    <el-form
      class="w-4/5 sm:w-1/2 lg:w-1/3 xl:w-1/4 m-auto"
      :ref="formRef"
      :model="form"
      :rules="rules"
    >
      <h2>Login</h2>
      <el-form-item label="Email" prop="email">
        <el-input
          type="email"
          autocomplete="off"
          v-model="form.email"
        />
      </el-form-item>
      <el-form-item label="Password" prop="password">
        <el-input
          type="password"
          autocomplete="off"
          v-model="form.password"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="success"
          class="w-full"
          @click="handleLogin"
        >Submit</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, onMounted, reactive, ref } from "vue";
export default defineComponent({
  name: "Login",
  setup() {
    const form = reactive({
      email: "",
      password: ""
    });
    const rules = ref({
      email: [{
        required: true,
        message: "Email is required",
        trigger: "blur"
      }],
      password: [{
        required: true,
        message: "Password is required",
        trigger: "blur"
      }]
    });
    const formRef = ref("formRef");

    const handleLogin = () => {
      console.log(formRef)
      // Property 'validate' does not exist on type 'string'.
      formRef.value?.validate((valid: boolean) => {
        console.log(valid);
      });
    };

    onMounted(() => {
      console.log("Login mounted");
    });

    onBeforeMount(() => {
      console.log("Login onBeforeMount");
    });

    return {
      formRef,
      form,
      rules,
      handleLogin
    };
  }
});
</script>

Answer №1

There are a few errors present. When dealing with objects, it is essential to use reactive rather than ref.

Therefore, define your rules using the reactive method instead of ref.

const rules = reactive({
      email: [{
        required: true,
        message: "Email is required",
        trigger: "blur"
      }],
      password: [{
        required: true,
        message: "Password is required",
        trigger: "blur"
      }]
    });

There is no need to bind your ref in this manner:

 <el-form
          class="w-4/5 sm:w-1/2 lg:w-1/3 xl:w-1/4 m-auto"
          ref="formRef"
          :model="form"
          :rules="rules"
        >

Instead, I suggest declaring your formRef using HTML casting objects like this:

const formRef = ref<HTMLFormElement>();

I trust that this advice will be beneficial for you =)

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

Tips for making a sidebar sticky when scrolling

In order to keep the right-side bar fixed, I have implemented this javaScript function: <script type="text/javascript> $(document).ready(function () { var top = $('#rightsidebar-wrapper').offset().top - parseFloat($('#rightsideb ...

I'm currently in the process of creating a Firefox extension and my goal is to accurately count the total number of text boxes on a webpage while excluding any hidden text boxes. Can someone please

As I work on creating a Firefox extension, I am faced with the task of counting the total number of visible text boxes on a webpage while ignoring any hidden ones. Many webpages contain hidden text fields for future use, so my goal is to exclude these fr ...

The rationale behind organizing analogous variables into groups

Currently, I am grappling with determining the optimal logic for grouping parameters within a specified tolerance level. Let me illustrate this with an example... Task1: parameter1=140 Task2: parameter1=137 Task3: parameter1=142 Task4: parameter1=139 Task ...

The ways in which variables interact with arrays in JavaScript

Just starting out with programming (3rd day), so please be patient :) I've been working on a pay calculator to practice what I've learned so far, but I'm stuck when it comes to tax calculation. I was hoping someone could help me work through ...

JavaScript code to remove everything in a string after the last occurrence of a certain

I have been working on a JavaScript function to cut strings into 140 characters, ensuring that words are not broken in the process. Now, I also want the text to make more sense by checking for certain characters (like ., ,, :, ;) and if the string is bet ...

Combining multiple pipe collections in a single Gulp task for both CoffeeScript and JavaScript files

I've been working on creating a single scripts task that can handle both .coffee and .js files effectively: Coffee files need to go through coffee(), coffeelint() and coffeelint.reporter() JS files should run through jshint() All files then need to ...

The method of applying conditional formatting to an HTML table is dependent on the specific

I've come across some code that I want to tweak: conditional formatting of html table cells In my project, there are two different sets of formatting rules for a final table with 37 columns. Most of the columns will follow rule 1, while about 10 of ...

Navigating through the map function within Protractor

In my Angular application, I have implemented a timeline that displays event dates with their respective descriptions. Below is the HTML source code for this feature: <!-- timeline --> <h4 class="font-thin m-t-lg m-b-lg text-primary-lt">Hi ...

Struggling to successfully toggle the visibility of items

I am currently facing an issue with displaying different sets of data based on button clicks. The first block of information is showing correctly upon page load, but when I try to display other blocks by clicking on the corresponding buttons, the info cont ...

Issues with retrieving data using Node Express routes

I have a button that links to <a href="/data_entry?Display=AAA&ts=<%=dateStamp%><%=locTimeStamp%>">AAA</a> The route I defined is as follows: router.get('/data_entry/:Display/:ts', function(req,res){ console.lo ...

When the checkbox toggle is marked as checked, ensure that an input field within the toggle div is set as

Utilizing a script to toggle various div elements with JavaScript, I am seeking a way to designate certain input fields as "required" within the toggled div when a checkbox is checked. Can anyone provide guidance on how to achieve this functionality? fu ...

What is the best way to increase a React prop value?

Getting Stuck with a Counter Component Hello there! I am facing some challenges while trying to create a counter component for my online store. It seems like the functionality is not working as expected. The Issue at Hand It appears that the count value ...

What is the best way to mock an internal function within my route using sinon?

Currently, I have my own internal function defined in the greatRoute.ts file: //in greatRoute.ts async function _secretString(param: string): Promise<string> { ... } router .route('/foo/bar/:secret') .get( async (...) => { ...

What is the best way to change JSON into a key-value dictionary with TypeScript?

Here is a JSON example that I am working with: { "MyTest:": [{ "main": { "name": "Hello" }, "test2": { "test3": { "test4": "World" }, ...

Is there a way to create a timed fadeIn and fadeOut effect for a div using HTML and CSS?

I have a single div that initially displays text, and I want it to fade out after a specific time so that another div will then fade in. However, my attempt at coding this transition is not producing the desired result: $(function() { $(".preloa ...

Switching a button on and off in Vue.js

I am trying to create toggle buttons for the play and pause functions in Vue. Can someone please guide me on how to achieve this? Currently, this is the code I have: <button @click="slickPause" v-if="">slickPause</button> & ...

Exploring Angular's Subcomponents

While working on my application, I encountered a dilemma. I currently pass data from the main component to the subcomponents after pulling it from the API with a single request. Should I continue with this approach or have each component make its own separ ...

Optimizing the management of optional post fields in an Express.js application

When creating an endpoint with Express that includes both mandatory and non-mandatory fields in the post request, what is the optimal strategy for handling this? Would it be best to use something like if (field exists in req.body) { set variable } else { ...

An error occurs when attempting to redirect with getServerSideProps

When I am logged in, I want to redirect to the /chat page using auth0 for authentication. The error seems to be related to returning an empty string for props, but it does not impact the website as redirection works correctly. The main issue here is the in ...

Issue: Vue TypeScript module not foundDescription: When using

Is there anyone out there who can assist me with this issue regarding my tsconfig.json file? { "compilerOptions": { "target": "esnext", "module": "esnext", "moduleResolution": " ...