首页 > 解决方案 > How to attach event listener on each list item in Vue component?

问题描述

I have a component like this:

  Vue.component('navbar', {
  props: ['navitem'],
  methods: {
    users: function () {
        //users code
    },

    test:function(){
    }
  },
  template: '<li v-on:click="navitem.name"> {{navitem.name}} </li>'
  });

and i want to pass the following array to the component:

navitems: [{ id: 1, name: 'users' }, { id: 2, name: 'test' }]

and render them like this: v-for="item in navitems" v-bind:navitem="item" :key="item.id"

such that each list item get the corresponding event listener, that is the end rendered list items will be like this:

  <li v-on:click="users()"></li> 
  <li v-on:click="test()"></li>

how this can be done if possible?

标签: javascriptvue.js

解决方案


请记住,您将字符串传递给组件,而不是函数引用。要调用该函数,只需通过在组件对象中查找它来从组件中“选择”该函数,然后调用它。

Vue.component('navbar', {
  props: ['navitem'],
  methods: {
    users: function () {
        //users code
    },

    test:function(){
    },

    clickHandler(name) {
      this[name]();
    }
  },
  template: '<li v-on:click="clickHandler(navitem.name)"> {{navitem.name}} </li>'
});

推荐阅读