Use variable from v-slot in an event handler from same component

Hello there,

You can get variables exposed by a child component through the v-slot attribute. However, it looks like those variables cannot be used in an event handler of the same child component.

Example here:

<!-- Form.vue -->
<template>
  <form ref="HTMLFormElement">
    <slot v-if="HTMLFormElement" :el="HTMLFormElement" />
  </form>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const HTMLFormElement = ref();
onMounted(() => console.log(HTMLFormElement.value)); // <form>...</form>
</script>

<!-- App.vue -->
<template>
  <Form v-slot="{el}" @submit.prevent="() => submit(el)">
    <pre>{{ el }}</pre> <!-- [object HTMLFormElement] -->
    <button type="submit">
      Validate Form
    </button>
  </Form>
</template>

<script setup>
import { ref } from 'vue'
import Form from './Form.vue'

const submit = (el) => {
  console.log(el); // undefined
  el.reportValidity(); // Cannot read properties of undefined (reading 'reportValidity')
}
</script>

Playground: Vue SFC Playground

Is there another way to achieve this? I don’t want to handle the submit function in the submit button, as this one is sometimes somewhere else in the layout with a form attribute (on mobile, submit button moves to sticky footer) and I want people to be able to submit the form by hitting the Enter key.