Extend vueJs v-on directive: click

I am new to , I am trying to create my first application. I would like to show a confirmation message each time I click on the buttons.

Example:

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

My question is: can I expand the event v-on:clickto show confirmation worldwide? I would make my own directive called v-confirm-click, which will first execute a confirmation, and then if I click "ok", it will execute a click event. Is it possible?

+4
source share
2 answers

I would recommend the component. Vue directives are commonly used to directly manipulate the DOM. In most cases, when you think you need a directive, the component is better.

.

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

})

:

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

.

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/vue@2.2.6/dist/vue.js"></script>
<div id="app">
  <confirm-button :on-confirm="confirm" confirm-text="Are you sure?">
    Confirm
  </confirm-button>
</div>
Hide result
+5

, . confirm . , ; , .

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>
Hide result
0

Source: https://habr.com/ru/post/1682231/


All Articles