gpt4 book ai didi

javascript - VueJS 阻止对自定义事件的默认操作

转载 作者:搜寻专家 更新时间:2023-10-30 22:34:33 25 4
gpt4 key购买 nike

我有一个 <btn>由以下模板组成的组件:

<button @click="$emit('trigger')">
</button>

我在我的表单中使用这个组件是这样的:

<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 指定内联以防止 native 点击事件的默认行为:

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>

关于javascript - VueJS 阻止对自定义事件的默认操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46982019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com