0

I have a form in my Vue.js app with a submit button that triggers a loading spinner when clicked. Heres my code:

<script setup>
import { reactive } from 'vue'
import { router } from '@inertiajs/vue3'

defineProps({ errors: Object })

const form = reactive({
  email: null,
  password: null, 
  remember: null,
  loading: false
})
 
function submit() {  
    router.post('/login', form) 
}
router.on('start', () => {
  form.loading = true
})

router.on('finish', () => {
  form.loading = false
})


</script>

The HTML:

<form @submit.prevent="submit" action="post">
   <h5>Login </h5>
   <input v-model="form.email" type="text" ><label>Email</label>  
   <input v-model="form.password" type="password" ><label>Password</label>
   <button :class="form.loading ? 'spinner' : ''" type="submit" >{{form.loading ? "Processing..." : 'Login' }}</button>
   </form> 
<Link href="/register"> Register </Link>
<Link href="/home" ><i>home</i></Link>

For example when I click on the "register" link, the loading spinner appears even though the submit button was not clicked and that register link is also outside of the form scope. Can anyone help? I'm not sure how to fix it.

1
  • <Link> is part of the routing component, so clicking on that link should trigger the start event of the router, right? Thats how I see it. Commented Feb 14, 2023 at 11:35

1 Answer 1

0

use the useForm instead

import { useForm } from '@inertiajs/vue3';

const form = useForm({
    email: null,
    password: null, 
    remember: null,
    loading: false
});

const submit = () => {
    form.loading = true
    form.transform(data => ({
        ...data,
        remember: form.remember ? 'on' : '',
    })).post(route('login'), {
        onFinish: () => { 
            form.loading = false
            form.reset('password')
        },
    });
};

route('login') put the route name here instead of the link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.