[英]VueJS prevent default action on custom event
我有一个<btn>
组件,它包含以下模板:
<button @click="$emit('trigger')">
</button>
我在我的 forms 中使用这个组件是这样的:
<btn>Submit</btn>
现在有些情况下我需要在表单中有两个按钮。 其中一个提交表格,另一个不提交。 但是因为他们都在我的表单中,所以他们都提交了表单。 我不能做这样的事情:
<btn>Submit</btn> <!-- This button should submit the form -->
<btn @trigger="nextQuiz">Next</btn> <!-- This button should only execute the nextQuiz method -->
如何告诉 vue 仅在单击第二个<btn>
时阻止表单提交?
您可以通过@click.native.prevent
指定内联以防止本机click事件的默认行为:
Vue.component('btn', { template:` <button @click="$emit('trigger')"> <slot/> </button> ` }) new Vue({ el: '#app', methods: { nextQuiz() { console.log('nextQuiz') } } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script> <div id="app"> <form action=""> <input name="bar"> <btn>Submit</btn> <btn @click.native.prevent @trigger="nextQuiz">Next</btn> </form> </div>
设置类型 。
Vue.component("btn",{
props:{
submit: Boolean
},
computed:{
type() { return this.submit ? 'submit' : 'button' }
},
template: `
<button :type="type" @click="$emit('trigger')"><slot></slot></button>
`
})
像这样使用:
<form action="">
<btn submit>Submit</btn>
<btn>Don't Submit</btn>
</form>
这是一个例子。
console.clear() Vue.component("btn",{ props:{ submit: Boolean }, computed:{ type() { return this.submit ? 'submit' : 'button' } }, template: ` <button :type="type" @click="$emit('trigger')"><slot></slot></button> ` }) new Vue({ el: "#app" })
<script src="https://unpkg.com/vue@2.4.2"></script> <div id="app"> <form action=""> <btn submit>Submit</btn> <btn>Don't Submit</btn> </form> </div>
@thanksd与我的想法类似。 您也可以使用prevent修饰符。
Vue.component("btn",{
props:{
submit: Boolean
},
template: `
<button v-if="submit" @click="$emit('trigger')"><slot></slot></button>
<button v-else="submit" @click.prevent="$emit('trigger')"><slot></slot></button>
`
})
只要你的根元素是一个button
(在你的情况下),你也可以将类型设置为按钮,这将传递给按钮。 <button type="button">Click</button>
本身不会提交 forms。在您的情况下, <btn type="button">Click</btn>
不应提交表单。 这让你的 Vue 代码更简单。
<btn>Submit</btn> <!-- This button should submit the form -->
<btn type="button" @trigger="nextQuiz">Next</btn> <!-- This button should only execute the nextQuiz method -->
请参阅有关按钮类型的 MDN和有关按钮的HTML 规范。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.