admin管理员组文章数量:1391960
<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?
<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?
3 Answers
Reset to default 5You can't reference the Vue template variables from a vanilla javascript onclick
handler like you're trying to do.
You should pass the index value to a Vue @click
handler and call the vanilla javascript method from there:
function addPlant(idx) {
alert(idx)
}
new Vue({
el: '#app',
data() {
return {
groups: ['a', 'b', 'c']
}
},
methods: {
onButtonClick(idx) {
addPlant(idx)
}
}
})
<script src="https://cdnjs.cloudflare./ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(grp, idx) in groups">
<button @click="onButtonClick(idx)">
{{ idx }}
</button>
</div>
</div>
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 ponent:
new Vue({
el: '#app',
data(){
return{
bars:['a','b','c']
}
}
})
function addPlant(index){
console.log("# "+index)
}
<script src="https://cdnjs.cloudflare./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>
Create a Vue method calling the javascript function
methods: {
callAddPlant: function(idx) {
addPlant(idx)
}
}
...
<div v-for="(grp,idx) in vm">
<button v-on:click="callAddPlant(idx)">
.......
</button>
</div>
本文标签:
版权声明:本文标题:vue.js - How to pass vuejs for-loop index value as the parameter of HTML button onclick javascript function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744699648a2620489.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论