如何将 vuejs for-loop 索引值作为 HTML 按钮 onclick javascript 函数的参数传递 [英] How to pass vuejs for-loop index value as the parameter of HTML button onclick javascript function

查看:39
本文介绍了如何将 vuejs for-loop 索引值作为 HTML 按钮 onclick javascript 函数的参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<button onclick="addPlant(idx)">......

addPlant() 是一个 javascript 函数,而不是 VueJS 方法.

现在如何将 idx 值传递给 javascript 方法?

解决方案

如果我们仅限于您的特定用例,我们可以将 index 分配给 data-label属性(绑定到index)并传递this.getAttribute('data-label')作为参数,this 指的是 Html 元素,而不是 Vue 实例或组件:

new Vue({el: '#app',数据(){返回{条形:['a','b','c']}}})函数添加植物(索引){console.log("#"+index)}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script><div id="应用程序"><div v-for="(bar,idx) in bar"><button :data-label="idx​​" onclick="addPlant(this.getAttribute('data-label'))">{{酒吧}}

<div v-for="(grp,idx) in vm">
    <button onclick="addPlant(idx)">
    .......
    </button>
</div>

addPlant() is a javascript function and not a VueJS method.

How can I pass the idx value to the javascript method now?

解决方案

If we go to be limited to your specific use case we could assign index to data-label attribute (which is bound to index) and pass this.getAttribute('data-label') as parameter, this refers to the Html element not to the Vue instance or component:

new Vue({
  el: '#app',
  data(){
    return{
      bars:['a','b','c']
    }
  }
  
})

function addPlant(index){
  console.log("# "+index)
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
 <div v-for="(bar,idx) in bars">
    <button :data-label="idx" onclick="addPlant(this.getAttribute('data-label'))">
{{bar}}
    </button>
</div>
</div>

这篇关于如何将 vuejs for-loop 索引值作为 HTML 按钮 onclick javascript 函数的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆