【发布时间】:2020-08-10 13:20:37
【问题描述】:
我需要处理子组件中的事件;检查某个条件;如果为真,则将“提交”事件返回给父级,以便它的事件处理程序将运行。
下面的示例使用 Vue.js 2.6.11 触发父级的事件处理程序(将“vue”替换为“@vue/composition-api”)。在 3.0.0-rc.5 中,它会触发 两次。想知道这是故意更改、错误还是我。
App.vue:
<template lang="pug">
#app
.container
h1 Form Experiment
FormGroup(@submit='onSubmit')
button.btn.btn-primary(type='submit') Submit
</template>
<script lang="ts">
import { defineComponent } from "vue"
import FormGroup from "@/components/FormGroup.vue"
export default defineComponent({
name: "App",
components: {
FormGroup,
},
setup() {
const onSubmit = (): void => {
alert("Parent event handler")
}
return { onSubmit }
}
})
</script>
FormGroup.vue:
<template lang="pug">
form(@submit.prevent='onFormSubmit', novalidate, autocomplete='on')
slot Content needed in FormGroup
</template>
<script lang="ts">
import { defineComponent } from "vue"
export default defineComponent({
name: "FormGroup",
setup(_, { emit }) {
const check = ref(true) // evaluated elsewhere - simplified for this example
const onFormSubmit = (): void => {
if (check.value) {
alert("Form is valid - sending event to parent")
emit("submit")
} else {
alert("Form is not valid.") // so don't emit the event to parent
}
}
return { check, onFormSubmit }
}
})
</script>
关于为什么在 Vue.js 3.0.0-rc.5 中父级中的 onSubmit() 触发两次的任何想法?
【问题讨论】:
-
可能是由
<form>作为根元素引起的错误?如果 FormGroup 被植根为<div><form...,我会很好奇是否会发生同样的事情 -
@nstuyvesant 我刚刚在 Vue 2 中使用
@vue/composition-api尝试了您的代码,它也触发了两次,所以我认为这不是 Vue 3 中的错误。Daniel 的回答应该提供解决方案。
标签: typescript vue.js event-handling vuejs3 vue-composition-api