我有2个组件,一个用于“创建表单”,另一个用于“编辑表单” 我在'edit-form'中使用'create-form'。一切都运作良好,除了我的提交方法 我希望覆盖'create-form'的提交事件,但它总是首先被调用 我有可能和正确的方法吗?这也是我想要实现的目标: https://jsfiddle.net/DarkFruits/197wndq9/1/
HTML
<template id="form-create">
<form @submit.self.prevent="raiseSubmit">
<button type="submit">SUBMIT</button>
</form>
</template>
<template id="form-edit">
<form-create v-bind:user="myUser" @submit.stop.capture.prevent="raiseSubmit" ></form-create>
</template>
<div id="app">
<form-edit></form-edit>
</div>
JS
Vue.component('form-create', {
template: '#form-create',
props: {
user: {
default: {
username: '',
email: '',
}
}
},
methods: {
raiseSubmit() {
console.log("I do not want Create submit to be called");
}
}
})
Vue.component('form-edit', {
template: '#form-edit',
data() {
return {
myUser: {
username: 'max',
email: 'max@example.com'
}
}
},
methods: {
raiseSubmit() {
console.log("I want Edit submit to be called");
}
}
})
new Vue({
el: '#app',
data() {
return {}
}
})
答案 0 :(得分:2)
如果要覆盖组件中的某些内容,则需要对组件进行编码以允许覆盖。一种方法是添加一个布尔prop,如果设置,组件会发出一个提交事件(有效冒泡),但如果没有,它会运行其常用的处理程序。
Vue.component('form-create', {
template: '#form-create',
props: {
user: {
default: {
username: '',
email: '',
}
},
defer: {
type: Boolean,
default: false
}
},
methods: {
raiseSubmit(e) {
if (this.defer) {
this.$emit('submit', e);
} else {
console.log("I do not want Create submit to be called");
}
}
}
})
Vue.component('form-edit', {
template: '#form-edit',
data() {
return {
myUser: {
username: 'max',
email: 'max@example.com'
}
}
},
methods: {
raiseSubmit() {
console.log("I want Edit submit to be called");
}
}
})
new Vue({
el: '#app',
data() {
return {}
}
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<template id="form-create">
<form @submit.prevent="raiseSubmit">
{{user.username}}
<button type="submit">SUBMIT</button>
</form>
</template>
<template id="form-edit">
<form-create v-bind:user="myUser" defer @submit.prevent="raiseSubmit"></form-create>
</template>
<div id="app">
<form-edit></form-edit>
</div>