How to pass vuejs for-loop index value as the para

2019-07-16 05:39发布

<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条回答
Luminary・发光体
2楼-- · 2019-07-16 06:15

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>
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-16 06:28

You 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.com/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>

查看更多
不美不萌又怎样
4楼-- · 2019-07-16 06:29

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>

查看更多
登录 后发表回答