With Vuejs, how to use a modal component inside a v-for loop the right way

These two links helped me figure this out:

  • https://v2.vuejs.org/v2/examples/modal.html

  • https://laracasts.com/discuss/channels/vue/passing-data-form-v-for-loop-to-modal-component

#In your Parent Component You don't have to create a modal for each item within the v-for loop, simply include the modal-component at the beginning of your parent and then work with v-if="..." and props.

<template>
  <div>
    <modal v-if="modalVisible" @close="modalVisible = false" :data="modalData"/>

    <div v-for="item in items">
      <button type="button" @click="openModal(item)">Open Modal</button>
    </div>

  </div>
</template>

and then in your script:

import modal from './Modal'

export default {
  components: {
    modal
  },
  data() {
    return {
      modalVisible: false,
      modalData: null
    }
  },
  methods: {
    openModal(data) {
      this.modalData = data
      this.modalVisible = true
    },
  }

#In your child (modal) component In your modal you can now do the following:

Template:

<template>
    {{ data.foo }}
    <button @click="$emit('close')">Cancel</button>
</template>

Script

<script>
  export default {
    props: ['user']
  };
</script>

Hope that helps :-)