The comparison between using multiple Vue.js instances and components, and implementing Ajax tabs

I am looking to incorporate ajax tabs using vue js. Each tab will need an ajax request to fetch both the template and data from an api.

Here is an example of the tabs:

<div id="tabs">
  <ul class="nav nav-tabs">
    <li class="active"><a href="#tab1" role="tab" data-toggle="tab">Tab1</a></li>
    <li><a href="#tab2" ajax-url="/tab2" role="tab" data-toggle="tab">Tab2</a></li>
    <li><a href="#tab3" ajax-url="/tab3" role="tab" data-toggle="tab">Tab3</a></li>
    <li><a href="#tab4" ajax-url="/tab4" role="tab" data-toggle="tab">Tab4</a></li>
  </ul>

  <div class="tab-content">
    <div role="tabpanel" class="tab-pane active" id="tab1"></div>
    <div role="tabpanel" class="tab-pane" id="tab2"></div>
    <div role="tabpanel" class="tab-pane" id="tab3"></div>
    <div role="tabpanel" class="tab-pane" id="tab4"></div>
  </div>
</div>

<script>
$('#tabs').on('shown.bs.tab', function (event) {
   var url = event.target.getAttribute("ajax-url");
   // fetch template and data..
   // init vue instance for the new tab
})
</script>

What would be the most effective way to integrate vue into this setup? Should I create separate vue instances for each tab, or use components? Additionally, I require the ability to preload some of the tabs.
Given that I need to initialize the vue instances on demand, I am uncertain about the best approach to handle this. In angular, I would define ng-controller for each tab. However, with vue.js it seems there may not be a standardized project architecture.

Answer №1

Utilize vue-router for organizing tabs.

Each tab will load a distinct View/Component when activated, leveraging the preloaded code in the vue.js bundle file.

The use of Vue Lifecycle hooks, like created and mounted, is commonplace for setting up or fetching additional data in each View.

It seems that your scenario is coherent enough to be managed by a single vue instance without the need for jQuery/AJAX.

If there are significant variations in your use-cases, it might be more efficient to construct multiple separate components, each compiled into their own JS file (typically achieved with Webpack's multiple 'entry' configuration).

UPDATE

You can bundle Vue components using the CLI; refer to: Compile .vue file into .js file without webpack or browserify

Note that each Component can mount a separate tab using the el attribute, similar to Angular's 'ng-controller' directive:

new Vue({
  el: '#tab1',
  data () {
    return {
      obj
    }
  }
})

However, attempting to control Vue instances externally from Vue (e.g., using jQuery) is generally discouraged.

If you opt for Webpack, Bootstrap can still be utilized. There are various methods to integrate Bootstrap, personally recommending importing the SCSS. Keep exploring online resources to support your progress.

Answer №2

If you prefer not to use the vue-router, it's recommended to utilize separate Vue instances. However, this approach may lead to memory leaks and other issues. To mitigate these issues, ensure that when making an AJAX request upon clicking a tab, you first destroy the current Vue instance before adding data to the DOM.


let app = new Vue({
    el: '#app',
})
// perform other actions
$.ajax({
    // ajax settings
    success: function(data){
        // ensure to destroy the old Vue instance here to prevent any potential issues
        app.$destroy()
        $('body').html(data);
    }
})

A more efficient solution would be to create a small JavaScript plugin. This plugin can handle AJAX requests when a link is clicked, fetch the data, and update the page while ensuring to destroy the previous Vue instance. Additionally, you can implement callbacks for loading indicators like page loaders.

In one of my projects, I implemented a jQuery AJAX-based plugin as shown below:


import $ from 'jquery';
import anime from 'animejs';

// Define Loader class
export let Loader = (function(window , document , undefined){

    // Constructor with initialization logic
    class Loader{

        constructor(options = null){
            // Configuration options
            this.options = Object.assign({ pageProgressBar : false , pageProgressBarDuraion: 2000 } , options);
            this.functions = [];
            this.xhr = null;
            this.routes = this.options.routes || [];

            window.addEventListener('load' , this.init.bind(this));
        }

        // Other methods and functionalities...

    }

    return Loader;

    // Private progress bar methods
    var $pageProgressBar = null;

    // Progress bar control functions

}(window , document , undefined));

The plugin comes equipped with progress bars and additional features which can be customized or removed according to your requirements. To implement the plugin, simply follow these steps:


window.Loader = new Loader({
    container: "#app-data",
})

Then, add the ajax-link attribute to the relevant tab links in your case. This will dynamically load content into the specified container. You can also utilize callback functions such as

Loader.beforeLoading = function(){
            app.$destroy();
        }
for added functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving values from a multidimensional array in JavaScript

I need some help with my code. I am struggling to pass an array (larray3) containing elements from two other arrays (larray1 and larray2) from data.js to model.js and view.js. Despite correctly building the multidimensional array in data.js, when I receive ...

Is there a way to extract dates from multiple date pickers using Vuetify?

Here is the script I'm working on: <template> <v-container> <v-dialog v-for='foo in foos' :key='foo.id' :close-on-content-click="false" transition="scale-transition" ...

How can we stop the anchor jump caused by a third-party script?

I'm currently utilizing a third-party script (details provided below) to divide a form into multiple ajax'd pages. However, when I attempt to move on to the next page, it immediately jumps to an anchor at the top of the form. This behavior is unn ...

Troubleshooting AngularJS $q Promise Not Being Returned

I have encountered an issue while trying to call a service method in AngularJS. The service method is being called successfully, but it is not returning any value to the controller function that invoked it. If anyone can offer assistance, I would greatly ...

Click on the form to initiate when the action is set to "javascript:void(0)"

I am working on an HTML step form that needs to be submitted after passing validation and ensuring all fields are filled. The form currently has an action controller called register.php, but also includes action="javascript:void(0);" in the HTML form. What ...

Is it possible for me to overlap a text over hidden text, and if the hidden text becomes visible through JavaScript, my text will shift to the right of the now visible hidden text?

I'm currently working on a website for a company that requires users to complete all the information before proceeding. To achieve this, I created a form with the following code: <form action="Owners Infoback.php" onsubmit="return validateFo ...

Regularly updating a book's interactive pages with turn.js technology

I experimented with generating dynamic content in turn.js using the sample provided here. This is an excerpt of the code I have written: <body> <div id="paper"> </div> </body> <script type="text/javascript"> $(win ...

Issue with PeerJs Localhost Setup

Implementing the zoom clone with WebRTC using peerjs, I am facing an issue where myPeer.on("call", (call) => { is not getting called. This code works fine for others on localhost who followed the tutorial on the zoom clone. I am unsure of what ...

AppProps in Next.js - Ensure that you have the correct loader set up to handle this specific file type as there are currently no loaders configured for processing it

I've encountered an issue while working on a Next.JS 13.5.6 application in development mode. When I try to connect to the site, I receive an error message. However, everything works fine when I switch to production mode after building and starting the ...

Tips for accessing a jQuery tab UI that is on a separate page by utilizing AJAX techniques

My project is a web application built in Eclipse using JSP, AJAX, and jQuery. It consists of two main JSP pages - home.jsp and second.jsp. Additionally, there are separate folders for css and js files. In second.jsp, I have implemented tab panels using di ...

Retrieve data with a web API

I am currently developing a web API to fetch data from a mock database using express My goal is to retrieve a JSON list containing all portfolios and their corresponding positions from the database module. Is there a way to structure the returned data so ...

How can I style the empty text in an ExtJS grid using CSS?

Is there a specific CSS class for a grid's emptyText? After inspecting the element with Firebug, all I found was: <div id="gridview-1021" class="x-component x-grid-view x-fit-item x-component-default x-unselectable" role="presentation" tabindex=" ...

Axios - retrieving merchandise

I have created an endpoint that retrieves all product information in JSON format. I am attempting to display this data on my index.html page using Axios, but I am encountering difficulties with getting the data correctly. This is my first time working with ...

Interacting with jQuery through JSON requests and decoding them in PHP

I've spent hours scouring through various online resources like StackOverflow and Google in search of a solution to get my ajax functionality working. My goal is to send data using json to a php form, then decode the json in php, process it, and final ...

Create a custom route variable in Node.js with Express framework

Is there a way to achieve this particular task using express.js? In my express.js application, I have set up a route like so: app.get('/hello', (req, res) => { // Code goes here }); This setup is functional, but I am curious if it is poss ...

What is the best way to execute two asynchronous calls sequentially in JavaScript?

When using a common generic function for AJAX calls, the initial request retrieves all data from the server and maintains it within local scope. However, subsequent requests are still hitting the server, even when the data is already available locally. Thi ...

Angular functions are executed twice upon being invoked within the html file

I decided to kick-start an Angular project, and I began by creating a simple component. However, I encountered a perplexing issue. Every time I call a function in the HTML file from the TypeScript file, it runs twice. TS: import { Component, OnInit } from ...

Executing Python script from PHP using an AJAX request

Hello, I am facing an issue with running a Python script from PHP on the client side using an AJAX call. Here is the code snippet: $.ajax({ async: false, cache:false, url:"callpython.php", type: "POST", data: "data1=" + path + "&data2=" + clr[k0], s ...

Updating the $location variable from the $rootScope perspective

I am facing an issue with my web app which is built using AngularJS. I have two functions in my code - one declared on the $rootScope and the other on the $scope. The code snippets are shown below: app.js app.run(function ($rootScope, $location) { $roo ...

Expanding the width of a Datatables within a Bootstrap modal

While working on my modal, I encountered an issue with the width of Datatables. Despite trying to adjust it to fit the modal size, it appears like this: Below is the jQuery code calling the Datatables: function retrieveTags(){ var identifier = $(&a ...