Encountering a unique edge case, I found a solution. When creating a form with Vue, I noticed that empty strings were being sent to the server. Upon investigation, it became apparent that the issue lies within the @submit
directive. Interestingly, when utilizing form.addEventListener('submit')
, the functionality works correctly, contrary to using @submit
.
The workaround involves using the addEventListener method, raising questions about potential errors on my end or if this is a bug related to Vue's v-on directive.
For a runnable example, refer to: https://stackblitz.com/edit/web-platform-izreva?file=index.html
NOTE: Familiarity with the form data object and viewing it can be attained through:
for (const [key, value] of formData.entries()) {
console.log(`${key}: ${value})
}
In the snippet below, uncommenting the code enables proper functionality with the addEventListener approach.
const form = document.querySelector('#test-form')
const app = Vue.createApp({
name: 'test app',
methods: {
test(e) {
e.preventDefault()
console.log(e)
const formData = new FormData(form)
for (const [key, value] of formData.entries()) {
console.log(`${key}: ${value}`)
}
}
}
}).mount('#app-main')
// const form = document.querySelector('#test-form')
// form.addEventListener('submit', e => {
// e.preventDefault()
// const formData = new FormData(form)
// for (const [key, value] of formData.entries()) {
// console.log(`${key}: ${value}`)
// }
// })
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="acdad9c9ec9f829e82989b">[email protected]</a>/dist/vue.global.js" defer></script>
</head>
<body>
<h1>app</h1>
<div id="app-main">
<form @submit="test" id="test-form">
<input type="text" name="foo">
<button type="submit">submit</button>
</form>
</div>
<script src="./index.js" defer></script>
</body>
</html>