英文:
laravel Inertia vue form event triggered even on non-submit button
问题
以下是代码的翻译部分:
我在我的Vue.js应用程序中有一个表单,其中有一个提交按钮,当单击时会触发加载动画。以下是我的代码:
<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>
HTML:
<form @submit.prevent="submit" action="post">
<h5>登录 </h5>
<input v-model="form.email" type="text" ><label>邮箱</label>
<input v-model="form.password" type="password" ><label>密码</label>
<button :class="form.loading ? 'spinner' : ''" type="submit" >{{form.loading ? "处理中..." : '登录' }}</button>
</form>
<Link href="/register"> 注册 </Link>
<Link href="/home" ><i>主页</i></Link>
例如,当我点击“注册”链接时,加载动画出现,尽管提交按钮没有被点击,而且该注册链接也在表单范围之外。有人可以帮忙吗?我不确定如何修复它。
英文:
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
得分: 0
使用 useForm
替代
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')
在此处放置路由名称而不是链接。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论