vue.js - 如何在 v-for 和 v-on:click 中同时获取索引和事件?
问题描述
这是一个简单的 vue 演示:
<body>
<div id="app">
<ul>
<li v-for="text,i in todoList" v-on:click="method_1(i)" >{{text}}</li>
</ul>
<ul>
<li v-for="text,i in todoList" v-on:click="method_2" >{{text}}</li>
</ul>
<ul>
</ul>
</div>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js"></script>
<script>
new Vue({
el:"#app",
data:{
todoList:["aaaaa",'bbbbbb','ccccc']
},
methods:{
method_1:function(i){
console.log(i) // i is index of v-for
},
method_2:function(e){
console.log(e)
},
}
})
</script>
</body>
我想绑定 onclick 函数并将event
andindex from v-for
作为这个函数的参数。
如果我使用v-on:click="method_1(i)"
:
-- vue 将这个取i
之前的变量;
eles 如果我使用v-on:click="method_1
:
-- vue 会自动click event
作为参数。
但是我想要click event
之前的变量和变量作为我函数的参数。我该怎么做?
解决方案
To use both events and params, you need to have something like example($event, params)
Using your example,
<li v-for="(text, i) in todoList" v-on:click="method_1($event, i)">
{{ text }}
</li>
methods: {
method_1: function(ev, i){
console.log(ev) // this is the event
console.log(i) // i is index of v-for
}
}
推荐阅读
- reactjs - 过期后自动获取新token
- html - 带有多行文本的标签内的中心复选框
- html - 在网页中过滤和显示数据库的内容
- excel - 使用 xlwings 打开 Excel 时如何单击“启用宏”?
- laravel - Laravel 5.7 和字体真棒
- java - REST API,不能在我的 URL 中输入“%20”或“+”作为空格。未获取 URL
- css - 当属于不同的行时,堆叠标签和控件“纵横交错”
- reactjs - 动画滚动到加载的元素
- ms-access - 查找空子报表并将其隐藏在 Access 报表中的属性/功能
- javascript - 为什么脚本在浏览器显示页面之前完成