如何在li生成的动态vuejs上使用事件处理程序

时间:2017-11-11 13:15:26

标签: javascript html vue.js

我正在生成一堆带有v-for的ul

<div v-for="item in info">
  <ul>
    <li><a>{{item.number}}</a></li>
    <li><a>{{item.alphabet}}</a></li>
  </ul>
</div>

我有像这样的vue组件

 export default {
      name: 'Zone',
      data(){
          return{
            info:'[
    {'alphabet':'a','number':1},
    {'alphabet':'b','number':2},
    {'alphabet':'c','number':3}
    ]'

          }
      },
   methods:{
   clicked:function(){
     console.log(this)
      //console.log(this.value)
       //console.log(this.text)
   }
 }
    }

我希望在按下li时获取li元素的值。我尝试过使用'this',但没有用。我应该如何在vueJS中解决这个问题

3 个答案:

答案 0 :(得分:1)

您可以尝试将该项作为参数传递给您的函数。像这样:

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);
    }
  }
});

和模板:

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

注意clicked方法中的这个引用了注释中指向的Vue实例。

查看this fiddle

答案 1 :(得分:1)

您可以查看此内容。您只需在@click

上添加ul即可

&#13;
&#13;
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)
   }
 }
  
})
&#13;
<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>
&#13;
&#13;
&#13;

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

答案 2 :(得分:1)

&#13;
&#13;
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)
    }
  }
})
&#13;
li {
  border: 1px solid black;
}
&#13;
<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>
&#13;
&#13;
&#13;