Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add two methods on a @click event using vue.js?

This is my code and i basically want to add CHANGEBUTTONS to the on click event that looks like @click.

<button @click="enviarform2" value="Delete from favorites" style="font-weight: 700;color:#428bca;margin-left:30px;height:30px;border-radius:4px" name="delete" v-else>Delete from favorites</button>


<script>
new Vue({
  el:'#app',
  data:{
    show: true,
    paletteid : <?=$palette_id;?>,
    action: "add",
    action2: "delete",
    number: ""
  },
  methods: {
           enviarform: function() {
            axios.post('/validarfavorite.php', {
                paletteid: this.paletteid,
                action: this.action
              })
              .then(function (response) {
                console.log(response);
              })
              .catch(function (error) {
                console.log(error);
              });
              this.number = "Yours plus ";
          },
           enviarform2: function() {
            axios.post('/validarfavorite.php', {
                paletteid: this.paletteid,
                action2: this.action2
              })
              .then(function (response) {
                console.log(response);
              })
              .catch(function (error) {
                console.log(error);
              });
              this.number = "Minus yours plus ";
          },
          changebuttons: function() {
            this.show = !this.show;
          }
        }
});
</script>

I have tried with method 1 and method 2 and handler but it didnt work. Hope you know!

like image 849
Franco Maldonado Avatar asked Mar 10 '18 13:03

Franco Maldonado


2 Answers

You can separate the calls using a ; (or the comma operator):

<button @click="@click="m1(); m2()">my button</button>

<button @click="@click="m1(), m2()">my button</button>

But if your code is used in more than one place, though, the best practice (the "cleanest approach") is to create a third method and use it instead:

<button @click="mOneAndTwo">my button</button>

Demo:

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    m1: function() { this.message += "m1"; },
    m2: function() { this.message += "m2"; },
    mOneAndTwo: function() {
       /* call two methods. */
       this.m1();
       this.m2();
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <button @click="m1(); m2()">call two methods using ;</button><br>
  <button @click="m1(), m2()">call two methods using ,</button><br>
  <button @click="mOneAndTwo">call two methods using a third method</button><br>
</div>
like image 198
acdcjunior Avatar answered Oct 22 '22 12:10

acdcjunior


The easiest way to do it is:

<button v-on:click="method1(); method2();">Continue</button>
like image 20
Franco Maldonado Avatar answered Oct 22 '22 11:10

Franco Maldonado