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

标签 javascript vue.js vuejs2

我有一个 <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/

相关文章:

c# - 隐藏元素内的数组 javascript

javascript - Vuetify 数据表条件列渲染

javascript - 由于 <template> 在 HTML 中内联,Vue.js 2.0 在 Edge 中为空白

javascript - 构建 Vue.js 项目时使用 Gridsome 时出现 TypeError

vue.js - VueJS |方法 "watch"在组件定义中具有类型 "object"

javascript - 进行 Javascript 函数调用监听器/按键的最灵敏的方式是什么

javascript - jqueryMobile 应用程序无法使用 jquryMobile 框架 js 和 css 文件相对路径

javascript - 无法在 react-split-pane 中调整两个 Pane 的大小

javascript - Vuejs 实现全局确认对话框功能时遇到的问题

javascript - 表行上的 Vuejs 转换