Gerald Bern
Gerald Bern

Reputation: 61

How to open a different modal on each tab?

I'm trying to open a modal on each tab item but the modal only opens on the first tab. If I click on any item other than the first and try to open the modal, it will be open on the first item.

The other problem is that I can't open a modal when I add new items. Starting tabs = [] does not work. How to solve it?

see an example

https://jsfiddle.net/gerald3ebd/k7abtf35/

Upvotes: 1

Views: 1245

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34924

All three tab's are targeting to same modal, make it separate/different by changing id/href as different.

Vue.use(VueTabs);
new Vue({
  el:"#app",
  data:{
    tabs: ['First tab', 'Second tab', 'Third tab']
  },
  methods: {
    removeTab(index){
      this.tabs.splice(index, 1)
    },
    addTab(){
      this.tabs.push('New Tab');
      var vm = this;
      setTimeout(function(){
          var elems = document.querySelectorAll('#modal'+(vm.tabs.length-1));
          M.Modal.init(elems);
      },100);
       
    }
  },
  mounted() {
    document.addEventListener('DOMContentLoaded', function() {
        M.AutoInit()
        var elems = document.querySelectorAll('.modal');
        M.Modal.init(elems);
      })
  }
})
.tab-close{
  float:right;
}
.tab-close:hover{
  transform: rotate(7deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://rawgit.com/cristijora/vue-tabs/master/dist/vue-tabs.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/cristijora/vue-tabs/master/themes/material.css">
<link rel="stylesheet" href="https://rawgit.com/lykmapipo/themify-icons/master/css/themify-icons.css">

<div id="app">
 <button @click="addTab">Add new tab</button>
 <vue-tabs type="pills">
    <v-tab v-for="tab,index in tabs" :key="tab">
       <div slot="title">{{tab}} <span @click.stop="removeTab(index)" class="ti-close tab-close"></span></div>
       {{tab}} 
         <!-- Modal Trigger -->
          <a class="waves-effect waves-light btn modal-trigger" :href="'#modal'+index">Modal_{{index}}</a>

          <!-- Modal Structure -->
          <div :id="'modal'+index" class="modal">
            <div class="modal-content">
              <h4>Modal Header</h4>
              <p>A bunch of text</p>
            </div>
            <div class="modal-footer">
              <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a>
            </div>
          </div>
    </v-tab>
</vue-tabs>

</div>

Upvotes: 1

Related Questions