6

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?

2 Answers 2

7

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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>

1 Comment

thank you roy, it is a way, but i prefer create a component as suggest Bert Evans, anyway thankyou! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.