vue.js - 如何在 v-for 和 v-on :click? 中获取索引和事件

标签 vue.js

这是一个简单的 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>

我想绑定(bind) onclick 函数并将 eventindex from v-for 作为这个函数的参数。

如果我使用 v-on:click="method_1(i)":

-- vue 将此取 i 之前的变量;

eles 如果我使用 v-on:click="method_1 :

-- vue 会自动将 click 事件 作为参数。

但我想将 click 事件 和 before 变量都作为我函数的参数。我该怎么做?

最佳答案

要同时使用事件和参数,您需要有类似example($event, params)的东西

使用你的例子,

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

关于vue.js - 如何在 v-for 和 v-on :click? 中获取索引和事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50188465/

相关文章:

javascript - Vuejs 将现有匿名对象分配给 data 属性中的属性

javascript - nextTick : "TypeError: Cannot read property ' key' of undefined"in vue 错误

javascript - For Loop 项目未添加到购物篮中

vue.js - Vue.js属性或方法 “addToCart”未在实例上定义

javascript - vue.js 从表单选择中更新不同的模型

vue.js - 如何将外部 Vue 模板包含到 HTML 文件中

vue.js - Vue-MultiSelect:一次使用两个多选以及如何根据其他中显示的内容隐藏选项

javascript - Vue.js 和 Vuetify 槽作用域

javascript - 推送到组件页面Vue时的递归

javascript - 如何在 watch 模式下进行任何 mocha 测试之前运行全局设置脚本