javascript - 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?
解决方案
请记住,您将字符串传递给组件,而不是函数引用。要调用该函数,只需通过在组件对象中查找它来从组件中“选择”该函数,然后调用它。
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>'
});
推荐阅读
- oauth-2.0 - 从开发的角度来看,OAuth 和 OIDC 与 SAML 相比有什么优势,反之亦然?
- python - 两个不同维度数组的反向相加
- python - 如何检查给定日期恰好是一个月前:python
- google-bigquery - 通过 nodejs BigQuery Storage Write API 将行写入 BigQuery
- flutter - 在任何交互回调中使用 FutureBuilder 时,它的 future 方法被调用了两次
- rasa - Rasa 2.8 - 未检索到的实体
- python - Python 国际象棋数据 (FEN) 到 Stockfish for Python
- docker - 每次我在 Dockerfile 中使用 FROM 时,`docker build` 是否都会运行一个新容器?
- javascript - 在 JavaScript 中返回一个数组会返回 [object] 吗?
- python - 如何使 uWSGI 主线程不为 Django Web 应用程序提供请求?