amclelland
amclelland

Reputation: 29

How to create multiple Vue components inside of Bootstrap tabs?

I am using the togglable tabs component in Bootstrap. I would like a table in each tab. Each one is displaying a table of email logs (Click Event, Open Event, etc). I would also like each table to be loaded dynamically with Vue-resource only once the user clicks on that tab, and for the resource/component to only be loaded once (once we have the data from AJAX, don't refresh it).

How can I set this up? I currently have an email-table component and an email-table-template template that renders the table, but I'm not sure how to set those up to render themselves when the user clicks the tab, and to only call the AJAX once.

An illustration of the task

Here is my current code for detecting the tab switch and newing up a Vue component:

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var email_event = $(e.target).data('email-event');
switch(email_event) {
  case 'click':
    createClick();
    break;
  // rest of the cases
}

function createClick() {
var click_events = Vue.resource('/api/email_logs/click_events');

click_events.get().then((response) => {
  new Vue({
    el: '#table-click',
    data: {
      searchQuery: '',
      gridColumns: ['campaign_id', 'target_link_name', 'target_link_url', 'created_at'],
      gridData: response.body
    }
  })
});

Any insight is appreciated. Thanks very much!

Upvotes: 0

Views: 1727

Answers (2)

Duy Anh
Duy Anh

Reputation: 770

From official documentation

If you want to keep the switched-out components in memory so that you can preserve their state or avoid re-rendering, you can wrap a dynamic component in a <keep-alive> element

Sample:

<keep-alive> <component :is="currentView"> <!-- inactive components will be cached! --> </component> </keep-alive>

In the above example "currentView" is to be set to a component name you want to load/display

Docs: https://v2.vuejs.org/v2/api/#keep-alive

Upvotes: 0

leocoder
leocoder

Reputation: 196

If you want to call a method only once you can use listen and emit events.

vm.$once and vm.$emit should do the trick.

Official documentation https://v2.vuejs.org/v2/api/#vm-once

Here is a quick example https://jsfiddle.net/leocoder/s1nfsao7/4/

Upvotes: 1

Related Questions