LorenzoBerti
LorenzoBerti

Reputation: 6974

Extend Vue.js v-on:click directive

I'm new to . I'm trying to create my first app. I would like to show a confirm message on every click on buttons.

Example:

<button class="btn btn-danger" v-on:click="reject(proposal)">reject</button>

My question is: Can I extend the v-on:click event to show the confirm everywhere? I would make my custom directive called v-confirm-click that first executes a confirm and then, if I click on "ok", executes the click event. Is it possible?

Upvotes: 6

Views: 5876

Answers (2)

Roy J
Roy J

Reputation: 43881

I do not know of a way to extend a directive. It is easy enough to include a confirm call in the click handler. It won't convert every click to a confirmed click, but neither would writing a new directive; in either case, you have to update all your code to use the new form.

new Vue({
  el: '#app',
  methods: {
    reject(p) {
      alert("Rejected " + p);
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <button class="btn btn-danger" @click="confirm('some message') && reject('some arg')">reject</button>
</div>

Upvotes: 2

Bert
Bert

Reputation: 82459

I would recommend a component instead. Directives in Vue are generally used for direct DOM manipulation. In most cases where you think you need a directive, a component is better.

Here is an example of a confirm button component.

Vue.component("confirm-button",{
  props:["onConfirm", "confirmText"],
  template:`<button @click="onClick"><slot></slot></button>`,
  methods:{
    onClick(){
      if (confirm(this.confirmText))
        this.onConfirm()
    }
  }

})

Which you could use like this:

<confirm-button :on-confirm="confirm" confirm-text="Are you sure?">
  Confirm
</confirm-button>

Here is an example.

console.clear()

Vue.component("confirm-button", {
  props: ["onConfirm", "confirmText"],
  template: `<button @click="onClick"><slot></slot></button>`,
  methods: {
    onClick() {
      if (confirm(this.confirmText))
        this.onConfirm()
    }
  }

})

new Vue({
  el: "#app",
  methods: {
    confirm() {
      alert("Confirmed!")
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
  <confirm-button :on-confirm="confirm" confirm-text="Are you sure?">
    Confirm
  </confirm-button>
</div>

Upvotes: 7

Related Questions