[Vuejs]-How to use event handlers on li generated dynamically vuejs

1๐Ÿ‘

โœ…

You could try passing the item as a param to your function. Something like this:

var vm = new Vue({
  el: '#app',
  data: {
    info: [{
      'alphabet': 'a',
      'number': 1
    }, {
      'alphabet': 'b',
      'number': 2
    }, {
      'alphabet': 'c',
      'number': 3
    }]
  },
  methods: {
    clicked: function(item) {
      // `this` inside methods points to the Vue instance
      console.log(item);
    }
  }
});

and the template:

<div id="app">
  <ul>
    <li v-for="item in info">
      <a v-on:click="clicked(item)">{{item.number}}</a>
    </li>
  </ul>
</div>

notice that this inside the clicked method refers to the Vue instance as pointed in the comment.

Check out this fiddle.

๐Ÿ‘คAndrei Roba

1๐Ÿ‘

You can check this. You only need to add on @click on your ul

new Vue({
  el: '#app', 
  
 data () {
   return {
      info: [
        {'alphabet':'a','number':1},
        {'alphabet':'b','number':2},
        {'alphabet':'c','number':3}
      ]
   }
 },
 
 methods: {
   clicked (e) {
    let el = e.target.innerHTML
      console.log('you clicked on ', el)
   }
 }
  
})
<script src="https://unpkg.com/vue@2.5.3/dist/vue.js"></script>
<div id="app">
 <div v-for='item in info'> 
   <ul @click='clicked($event)'>
     <li>{{ item.number }}</li>
     <li>{{ item.alphabet }}</li>
   </ul>
 </div>
</div>

js fiddle https://jsfiddle.net/samayo/zvb4wdro/5/

๐Ÿ‘คsamayo

1๐Ÿ‘

new Vue({
  el: '#app',
  data: {
    items: [
      {id: 1, name: 'item1'},
      {id: 2, name: 'item2'},
      {id: 3, name: 'item3'},
      {id: 4, name: 'item4'},
      {id: 5, name: 'item5'}
    ]
  },
  methods: {
    showInfo (e) {
      console.log('ID: ' + e.target.getAttribute('id'))
      console.log('Content: ' + e.target.textContent)
    }
  }
})
li {
  border: 1px solid black;
}
<div id="app">
  <ul>
    <li
      v-for="item in items"
      :key="item.id"
      :id="item.id"
      @click="showInfo">
      {{ item.id }} - {{ item.name }}
    </li>
  </ul>
</div>

<script src="https://unpkg.com/vue@2.5.3/dist/vue.min.js"></script>
๐Ÿ‘คuser6748331

Leave a comment