[Vuejs]-How to display data from the nested object in Vue.js based on click event

2πŸ‘

It is pretty simple. You just need to attach an event listener with the @ prefix. That listener must be a method defined in the methods object on your vue object. Then you can just let the method receive the button object as a parameter. In my example I added a current property that is set by the method and contains the last pressed button. I also replaced the four buttons with one input and a v-for directive but it also works with buttons.

var app = new Vue({
  el: '#app',
  data: {
    buttons: [{
        id: 'btn1',
        name: 'button-1',
        number: 1,
        color: 'red'
      },
      {
        id: 'btn2',
        name: 'button-2',
        number: 2,
        color: 'blue'
      },
      {
        id: 'btn3',
        name: 'button-3',
        number: 3,
        color: 'orange'
      }
    ],
    current: {}
  },
  methods: {
    setCurrent(btn) {
      this.current = btn;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="button" v-for="btn in buttons" :id="btn.id" @click="setCurrent(btn)" :value="btn.name">
  <p>{{ current.id }}</p>
  <p>{{ current.name }}</p>
  <p>{{ current.number }}</p>
  <p>{{ current.color }}</p>
</div>
πŸ‘€Rain336

1πŸ‘

For Button:

<button id="btn1" name="" number="" color="" @click="set_SelectedButton(1)">One</button>

in Methods:

set_SelectedButton(value){
// or Based on condition how every you want
this.btn_id="value"
}


<h2>Clicked button data:</h2>

<p>{{ button[btn_id].id }}</p>
<p>{{ button[btn_id].name }}</p>
<p>{{ button[btn_id].number }}</p>
<p>{{ button[btn_id].color }}</p>
πŸ‘€Vignesh

0πŸ‘

You just need to create a function based on button number.

 <button id="btn1" name="" number="" color=""
   @click = "clickedOn(1)">One</button>
 <button id="btn2" name="" number="" color=""
   @click = "clickedOn(2)">Two</button>
 <button id="btn3" name="" number="" color=""
   @click = "clickedOn(3)">Three</button>

 <hr>
 <h2>Clicked button data:</h2>
 <p>{{ dataToShow.id }}</p>
 <p>{{ dataToShow.name }}</p>
 <p>{{ dataToShow.number }}</p>
 <p>{{ dataToShow.color }}</p>
</div>

You can check working example here:
https://jsfiddle.net/nud19tfz/

var app = new Vue({
  el: '#app',
  data: {
    buttons: [
      {
        id: 'btn1',
        name: 'button-1',
        number: 1,
        color: 'red'
      },
      {
        id: 'btn2',
        name: 'button-2',
        number: 2,
        color: 'blue'
      },
      {
        id: 'btn3',
        name: 'button-3',
        number: 3,
        color: 'orange'
      }
    ],
    dataToShow: {}
  },
  methods: {
   clickedOn: function(btnNum) {
    this.dataToShow = this.buttons[btnNum-1]
   }
 }
});
πŸ‘€Saloni

Leave a comment