Issue with Vue JS router component: Unable to reuse JavaScript file containing webpack imports after switching routes

Hey, I'm facing a bit of a complex issue here, but I'll do my best to explain it clearly. Currently, I'm using the latest versions of Vue and Vue-Router in my application with webpack.

The main component in question is called

CP.vue

<template>
...
</template>

<script>
    export default {
        data() {
            return {
            }
        },
        created() {
            Load();
            const JS = () => import('cp.js');
            JS();
            console.log("created");

        },
        mounted() {
            Show();
        },
        destroyed() {
            console.log("destroyed");
        },
        methods: { }

    }
</script>

And this is how cp.js starts

cp.js

console.log("cp created");

// Bootstrap Datepicker
import '../../../node_modules/bootstrap-datepicker/dist/css/bootstrap-datepicker.css';
// Switchery
import '../../../node_modules/mohithg-switchery/switchery.css';
// TreeView CSS 
import '../../../node_modules/patternfly-bootstrap-treeview/dist/bootstrap-treeview.css';
// Datatables CSS 
import '../../../node_modules/datatables.net-bs4/css/dataTables.bootstrap4.css';
// Datatables - Button CSS 
import '../../../node_modules/datatables-buttons/css/buttons.dataTables.scss';
/////////////////////////// Toastr - for warnings
import '../../../node_modules/toastr/build/toastr.min.css';
////////////////////////// ScrollBar 
import '../../../node_modules/perfect-scrollbar/src/css/main.scss';
// CSS
import '../../scss/pages/cp.scss';

.....
.... more JS code which never works the second time
.....

/*----------  DatePicker  ----------*/

const datePicker = $('#date-range').datepicker({
    toggleActive: true,
    format: 'dd/mm/yyyy',
    autoclose: true,
    daysOfWeekHighlighted: "0,6",
    weekStart: 1,
    endDate: 'today',
    maxDate: 'today',
    startDate: '01/01/2014'
});
/*----------  ScrollBar  ----------*/

$('#tree-container').perfectScrollbar();
// more code, but I've shortened it for brevity

^ The modules here are loaded using lazy-load. When I initially navigate to the path of CP.vue, the template displays and the JS file loads correctly. You can see "cp created" in the console. However, when I move to another component's path in the vue-router and then return to /cp, all the functionalities from cp.js stop working (date picker, etc), while the imported styles remain intact, and console.log("cp created") doesn't even execute, indicating that it only loads cp.js once, and when you revisit /cp, the script's functions are lost. This requires a page refresh for it to work again, which is not the ideal solution as I'm using VueRouter. I've searched high and low online for a solution, tried plugins like "vue-plugin-load-script" to unload and reload the script whenever the component is created and destroyed, but to no avail. Only the approach with using this code

const JS = () => import('cp.js');
JS();

Was successful in loading the js file because plugins like "vue-plugin-load-script" don't recognize esx syntax.

Anyone have a suggestion on how I can reuse cp.js every time the component is created again as I navigate between components in vue-router? Or perhaps a different approach that would effectively load that JS file... Appreciate any help!

Answer №1

It would be beneficial to consider a redesign of your code. The script is only evaluated once, and there may not be much you can do about it. This is the intended functionality.

cp.js:

export function initComponents()  {
  const datePicker = $('#date-range').datepicker({
    toggleActive: true,
    format: 'dd/mm/yyyy',
    autoclose: true,
    daysOfWeekHighlighted: "0,6",
    weekStart: 1,
    endDate: 'today',
    maxDate: 'today',
    startDate: '01/01/2014'
  });
  /*----------  ScrollBar  ----------*/

  $('#tree-container').perfectScrollbar();
}

and from your component:

import( /* webpackChunkName: "cp.js" */ 'cp.js').then(exports => {
  exports.initComponents();
});

EDIT: It is not ideal to define component ids in your custom file. It would be recommended to use vue-datepickers. There are many options available If you still wish to use a custom datepicker, you could pass htmlNode as a parameter to your initComponent function. However, creating a component named datePicker and placing all js code within the create method may be the better choice. Additionally, consider packaging your css files in a scoped css section instead of using global css.

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

The vue-cli 3.0 command runs on multi (webpack)-dev-server/client at the URL http://10.0.68.112:8080/sockjs-node, using webpack hot dev-server from ./src/main.js

While working on the project, I encountered an error when running vue-cli-service serve because the main.js file is not located in the src root directory. The error message reads as follows: * ./src/main.js in multi (webpack)-dev-server/client?http://10 ...

Ways to retrieve the chosen option in a dropdown list without specifying the dropdown's name, id,

Custom dropdown, Model-View-Controller Code @foreach (var attribute in Model) { string controlId = string.Format("product_attribute_{0}_{1}_{2}", attribute.ProductId, attribute.ProductAttributeId, attribute.Id); @switch (attribute.AttributeControl ...

Trouble with populating Ext.grid.Panel from ExtJS4 JSON data

Despite researching various posts on the topic, I am still facing issues. Even after attempting to create a Panel with minimal data, I cannot seem to make it work. This problem is really puzzling me. Below is the code snippet that I am currently working wi ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...

How can I obtain the width of one element and then use it to adjust the size of another element that is

Currently, I am working on a dropdown menu and facing an issue with setting the submenus to match the width of the top-level page. In my HTML structure (specifically for a WordPress theme), it looks something like this: <ul class="menu"> <li ...

Trouble encountered with card flip style login form in Vue.js, as the card is not maintaining its position properly during transition animations

Need help styling a login/signup component in Vue.js where flipping between the two cards isn't working smoothly. The transition is causing one card to move down and right while the other comes in from the bottom right. It's hard to explain the i ...

The error message "Property 'id' is missing on type 'T'" is indicating the absence of the 'id' property in the

I am currently working on a React component that serves as a table and is designed to handle various types of data. The structure of the component is defined as follows: type SimpleTableProps<T> = { data: Array<T>; ... }; const SimpleTabl ...

Leveraging the power of jQuery Ajax in conjunction with node.js and express for email validation functionality

Hey there! I have a contact form on my website that uses ajax for validation and email sending. The issue is that the validation file is set up for PHP, but I'm trying to make it work with my NodeJS app. Unfortunately, when I tried modifying the ajax ...

Add HTML syntax highlighting to a text area for coding purposes

I am facing a seemingly straightforward issue, but I worry that it may be too complex for me to handle on my own. My goal is to incorporate a textarea into a webpage where users can input HTML code, click a button, and have the interpreted HTML displayed i ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

Mocking Ext.Ajax.request in ExtJS 4.2.1 is a process of em

When it comes to frontend unit testing using Jasmine, one of the challenges I faced was mocking all the requests in my application. Luckily, I have already tackled a method to mock all my proxies successfully: proxy: appname.classes.proxy.ProxyNegotiator ...

Tips for preserving the status of radio buttons in a React application

I am currently utilizing a Map to keep track of the state of radio buttons, but I am facing challenges when it comes to correctly saving and updating it whenever a user makes a selection. The structure of my Map is as follows: { "Group A": [ ...

The JQuery function .load() is not functioning correctly

How can I dynamically load a webpage's content into a div using JavaScript and jQuery? Here's what I have tried: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> When a s ...

The SetInterval function will continue to run within a web component even after the corresponding element has been removed from the

I am currently engaged in developing a straightforward application that coordinates multiple web components. Among these components, there is one that contains a setInterval function. Interestingly, the function continues to run even after the component it ...

JavaScript alert causing disruption to Ajax requests

Currently, I am utilizing JQuery Ajax to retrieve a script from the server. $.ajax({ url: src, type: "GET", dataType: "script", timeout: transaction_timeout }).done(function(){}) .fail(function() { alert("Error in server");}) .always(funct ...

Using Regex to replace special characters in TypeScript

I need assistance in removing the characters "?" and "/" from my inner HTML string. Can you guide me on how to achieve this using regex? For example, I would like to replace "?" with a space in the following content. "Hello?How are you?<a href="http:/ ...

Is there a versatile spell-checking tool available for HTML text boxes?

When designing a text box in HTML, I want to provide real-time input validation and spell check for the user's text. My goal is to underline any spelling mistakes as they type. This seems like a basic feature, but I've yet to find a plugin or AP ...

Node.js Application with Role-Based Login

I am currently working on implementing role-based administration. When a user is created, the database stores a "1" for Admin or a "2" for a normal user. I want to retrieve this information from the database and display the corresponding start page based o ...

What is the correct way to utilize ng-if/ng-show/ng-hide to hide or show HTML elements within the app.run function

I am currently working on developing an app that loads views correctly. HTML: <body> <loading outerWidth='1000' outerHeight='1000' display='isReady'></loading> <div class='wrapper' ng-sho ...

Incorporate PNG files with pre-defined labels in a React element

In my application, there is a collection of PNG images with filenames consisting of only 2 letters like aa.png, ab.png, ac.png, and so on. Additionally, there is an API endpoint that retrieves an array of objects with a property "name" containing 3 letter ...