Extend Vue.js v-on:click directive
Asked Answered
T

2

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?

Toxin answered 25/7, 2017 at 15:6 Comment(0)
T
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>
Temperamental answered 25/7, 2017 at 15:14 Comment(0)
C
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>
Cockerel answered 25/7, 2017 at 15:39 Comment(1)
thank you roy, it is a way, but i prefer create a component as suggest Bert Evans, anyway thankyou! :)Toxin

© 2022 - 2024 — McMap. All rights reserved.