Vue.js 新手,尝试在表示表单的组件中处理提交事件,该表单将检查子组件的有效性,如果一切正常,则将处理传递给父组件中的事件处理程序。
我收到此错误... [Vue 警告]:v-on 处理程序中的错误:“TypeError: undefined is not an object (evalating '$event.preventDefault')”在 ---> at src/components/ MyForm.vue 在 src/App.vue
子组件是 MyForm...
<template lang="pug">
form(@submit.prevent='onFormSubmit', novalidate, autocomplete='on')
slot Content needed in MyForm
</template>
<script lang="ts">
import { defineComponent } from "@vue/composition-api"
export default defineComponent({
name: "MyForm",
setup(_, { emit }) {
const onFormSubmit = () => {
console.log("MyForm:onFormSubmit() - called first")
// Validate child components, if invalid, STOP, otherwise continue...
emit("submit") // errors
}
},
})
父组件(应用程序)...
<template lang="pug">
#app
.container
MyForm(@submit.prevent='onSubmit')
...other components
</template>
<script lang="ts">
import { defineComponent } from "@vue/composition-api"
import MyForm from "@/components/MyForm.vue"
export default defineComponent({
name: "App",
components: {
MyForm,
},
setup() {
const onSubmit = (): void => {
console.log("App.vue:onSubmit() - called second")
}
return { onSubmit }
}
</script>
或者,将 App 的 onSubmit() 函数作为道具传递给 MyForm 会更好吗?我可以在 MyForm 中进行验证然后调用传入的函数吗?