javascriptvue-componentvue-resourcevue.js

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!


Solution

  • 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/