2
<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 3

5

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.