我尝试使用相同的 vue 表单组件 "添加"模式和"编辑"模式使相同的形式两次无效。
逻辑是这样的:
-
主要组件"历史记录"从后端加载数据(Laravel( 如果数据存在,则加载"列表"组件并通过 props 传递数据 模式为"编辑"。
如果没有数据加载表单,则模式为"添加"。
历史.vue
<div v-if = "this.educations.length >0 ">
Status: {{ status }}
<list :educations="educations" :mode="mode.editvalue"> </list>
</div>
<div v-else>
<eduform :mode ="mode.addvalue"> </eduform>
</div>
- 这部分简单,工作正常。
- 在 eduform 组件中,我有两个按钮,它们显示依赖模式。
v-show="mode === 'add'"
或v-show="mode === 'edit'"
问题出在我的形式上:它完全杀死了我的方法!
<form @submit.prevent="mode === 'add' ? createEdu() : updateEdu() ">
这是我的方法:
createEdu() {
console.log(this.mode);
this.axios
.post(`/api/education/add/`, this.education)
.then((response) => {
this.$router.push({
name: 'education'
})
})
.catch(error => console.log(error))
}
这段代码出了什么问题? 谢谢。
我个人的观点是:尽可能避免在模板中使用 tenary 运算符。不应有条件地将方法绑定到submit
事件,而应直接将泛型方法绑定到提交事件。在泛型方法本身中,您将执行调用相应回调所需的任何检查。这使得你的模板更具可读性,并将复杂的逻辑抽象到 VueJS 组件的 JS 部分。
例:
<form @submit.prevent="onFormSubmit">
然后,在组件的 JS 部分,您可以执行以下操作:
onFormSubmit() {
if (this.mode === 'add')
this.createEdu();
else
this.updateEdu();
}
尝试从方法调用中删除括号。我相信当您添加方法作为事件处理程序时,这是处理它的正确方法。
这里解释得更好:https://forum.vuejs.org/t/difference-when-calling-a-method-function-with-or-without-brackets/41764/2