inertiajs / inertia

Inertia.js lets you quickly build modern single-page React, Vue and Svelte apps using classic server-side routing and controllers.
https://inertiajs.com
MIT License
6.37k stars 427 forks source link

Form helper inside Vue 3 Composition API cannot access methods #432

Closed ajnsn closed 3 years ago

ajnsn commented 3 years ago

Versions:

Describe the problem:

When using the Vue 3 Composition API with the @inertiajs/inertia-vue3 form helper, the methods of the form helper (post(), submit() etc.) only work when used inside the Options API or the template.

When using setup to expose your own method, an error is logged to the console, e.g.

Uncaught TypeError: form.post is not a function

Steps to reproduce:

<template>
    <form @submit.prevent="submit()">
        <button type="submit">Log in</button>
    </form>
</template>

<script>
import { useForm } from '@inertiajs/inertia-vue3'

export default {
  setup () {
    const form = useForm({
      email: null,
      password: null,
      remember: false,
    })

    function submit() {
        form.post('/');
    }

    return { form, submit }
  },
}
</script>

Fix

This issue occurs because the export in uses ref() instead of reactive(). I think ref() is more for primitive types.

export function useForm(data) {
  return ref(form(data))
}

Changing it to reactive() should fix this issue:

export function useForm(data) {
  return reactive(form(data))
}
leohubert commented 3 years ago

I have the same issue.

obennaci commented 3 years ago

For what it's worth, you can access the methods. It uses ref under the hood so you have to use .value inside setup(). eg: form.value.post('/')

That being said, using reactive is more appropriate for forms.

bebetoalves commented 3 years ago

I was facing the same problem and the docs is not clear about this.

Bobakanoosh commented 3 years ago

Also face the same issues. Approving #440 would be awesome.

reinink commented 3 years ago

A fix is coming for this in #575. 🙌

Thanks for your efforts here @ajnsn. 💜

rvanbaalen commented 2 years ago

I'm seeing exactly the same problem with

@inertiajs/inertia@0.11.0
@inertiajs/inertia-vue3@0.6.0

Edit: Scratch that. I had a form field called "submit". That was overwriting the form object's submit method.