簡體   English   中英

使用組合 API 在 Vue 中處理子項和父項中的提交事件

[英]Handle submit event in child then parent in Vue using Composition API

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() function 作為道具傳遞給 MyForm 會更好嗎? 我可以在 MyForm 中進行驗證,然后調用傳入的 function?

TL;博士:

從您的父應用程序中刪除.prevent

解釋:

如評論中所述,您不需要.prevent在您自己的父組件中。 .prevent on events 基本上可以防止默認事件傳播。 因此,例如,在您的form(@submit.prevent='onFormSubmit' ,當您的表單正常提交時(例如,通過按回車鍵),正常的提交事件被阻止,而是調用您的方法 onFormSubmit。

但是,在您的父組件中,沒有要阻止的默認 javascript 事件。 這就解釋了為什么你有錯誤TypeError: undefined is not an object (evaluating '$event.preventDefault') - 沒有$event ,所以它是undefined 並且undefined不是 object。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM