Importing JavaScript files to work with Vue-Router: A Step-by-Step Guide

Seeking guidance on importing JavaScript files correctly throughout my Vue project, including within the components used to implement changes with Vue-Router. Currently, encountering an issue where I must reload the component in order for the JavaScript to load properly; when navigating routes and changing components, the JavaScript functions only work after a manual refresh. It seems that I may not be including them correctly, as the Router Link alone is insufficient, leading to the Router View not loading the JavaScript for each component based on the route.

Here's a snippet from my index.html:

<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>vue-sfi</title>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="./static/Plugins/plugins/fontawesome-free/css/all.min.css">
    <!-- Ionicons -->
    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
    <!-- Tempusdominus Bootstrap 4 -->
    <link rel="stylesheet" href="./static/Plugins/plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css">
    <!-- iCheck -->
    <link rel="stylesheet" href="./static/Plugins/plugins/icheck-bootstrap/icheck-bootstrap.min.css">
    <!-- JQVMap -->
    <link rel="stylesheet" href="./static/Plugins/plugins/jqvmap/jqvmap.min.css">
    <link rel="stylesheet" href="./static/Public/css/material.css">
    <!-- Theme style -->
    <link rel="stylesheet" href="./static/Plugins/dist/css/adminlte.min.css">
    <!-- overlayScrollbars -->
    <link rel="stylesheet" href="./static/Plugins/plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
    <!-- Daterange picker -->
    <link rel="stylesheet" href="./static/Plugins/plugins/daterangepicker/daterangepicker.css">
    <!-- summernote -->
    <link rel="stylesheet" href="./static/Plugins/plugins/summernote/summernote-bs4.css">
    <link rel="stylesheet" href="./static/Public/css/styleSGB.css">
    <link rel="stylesheet" href="./static/Public/css/aside.css">
    
    // More links...
    
  </head>
  <body>
    <div id="app"></div>

<!-- JavaScript imports -->

// More script imports...

  </body>
</html>

If needed, here's the file structure for reference:

/
    |--> index.html
    |-->  /src
    |     |--> /components    <----Vue Router components
    |     |    |--> /interfaces
    |     |         |--> /afiliacion
    |     |              |--> afiliacion.vue
    |     |    |--> /layouts
    |     |         |--> /modules
    |     |              |--> aside.vue
    |     |              |--> footer.vue
    |     |              |--> header.vue
    |     |--> /router
    |     |    |--> index.js <----routes
    |     |--> App.vue
    |     |--> main.js
    |--> /static
         |--> /plugins <---- CSS and JavaScript files
         |--> /public  <---- CSS and JavaScript files.

Additionally, here's how the routes are set up:

// Route file

import Afiliacion from '@/components/Interfaces/Afiliacion/Afiliacion.vue'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login,
      meta: {
        requiresVisitor: true
      }
    },
    {
      path: '/logout',
      name: 'Logout',
      component: Logout
    },
    {
      path: '/Home',
      name: 'Layout',
      component: Layout,
      meta: {
        requiresAuth: true
      },
      children:[
         {
      path: 'Interfaces/Afiliacion',
      redirect: '/Home/Afiliacion',
      name: 'Afiliaciones',
      component:{
        render (c){ return c('router-view') }
      },
      children: [
        {
          path: '/AfiliacionFondo',
          name: 'Afiliacion',
          component: Afiliacion,
          meta: {
            requiresAuth: true
          }
        }]

Considering placing the CSS and JavaScript files in the src/assets folder as per common practice. Any assistance in resolving this issue would be greatly appreciated.

Answer №1

Simple method for incorporating jQuery into a vue project.

Install necessary packages

npm install vue-jquery --save

Add to main.js file

import vue-jquery from 'vue-jquery'

Vue.use(vue-jquery)

If you want to use external libraries in vue, npm installation is required. Then import it as shown above with jQuery.

Explore AdminLTE Vue

Check out the Vue AdminLTE by simply executing npm i.

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

Guide on verifying internet connection status using Ajax request

Ensuring authentication by checking the availability of network connection on mobile devices. To do this, we must have both a username and password. The authentication process will be conducted online, requiring an active internet connection on the device. ...

TypeScript does not perform type checking on arrays created using the Array() constructor and filled with the fill method

Using TypeScript version 2.4.2, compiled with the --target ES6 option has interesting results. For example, when using this line of code: var coins: { coin: number}[] = [1,1,1] TypeScript throws an error: Error TS2322: Type 'number[]' is no ...

Guide on converting a JSON containing nested JSONs into an HTML table

Currently, I am working with a JSON data structure that contains nested dictionaries. My goal is to create an HTML table where each top-level key serves as a column in the table. The inner key-value pairs should be represented as a single text within cells ...

Interact with visible elements by automating mouse clicks with puppeteer

When attempting to click on various elements within a page, my goal is to do so only if they are visible. While achieving this in selenium with the is_displayed method was simple, I have struggled to find a similar approach in puppeteer. I attempted to imp ...

Difficulty clearing dictionary in Vue.js causing issues with the DOM not updating

Check out this jsfiddle example I am working with a dictionary in Vue and using a v-for loop to render its items. I want to clear the dictionary, but simply setting it to an empty object or deleting keys doesn't trigger a re-render in the DOM. Any su ...

What is preventing the use of this promise syntax for sending expressions?

Typically, when using Promise syntax, the following code snippets will result in the same outcome: // This is Syntax A - it works properly getUser(id).then((user) => console.log(user) // Syntax B - also works fine getUser(id).then(console.log) However ...

Exploring the Difference Between $onChanges and $onInit in Angular Components

What sets apart the use of Controller1 compared to Controller2? angular.module('app', []) .component('foo', { templateUrl: 'foo.html', bindings: { user: '<', }, controller: Controller1, ...

Ways to ensure your Javascript code only runs based on the specific browser

I need a Javascript code to run depending on the browser version. Specifically, if the browser is not IE or is IE 9+, one piece of Javascript should be executed. If the browser is IE8 or lower, another piece of Javascript should be executed. My attempt to ...

Just initiate an API request when the data in the Vuex store is outdated or missing

Currently, I am utilizing Vuex for state management within my VueJS 2 application. Within the mounted property of a specific component, I trigger an action... mounted: function () { this.$store.dispatch({ type: 'LOAD_LOCATION', id: thi ...

JS - Activate the ghost element feature by using the preventDefault function

I am currently working on a project where I need to drag elements from a list of img tags to various svg:rect containers. The process involves using mousedown and mouseup events to track which img is being picked from the list and where it is dropped with ...

Add a plethora of images to the canvas

Just starting out with Fabric.js and trying to figure out how to draw a picture on the canvas after a drop event. I managed to do it once, but am struggling with inserting more pictures onto the canvas (each new drop event replaces the previous picture). ...

Leveraging the Request npm package synchronously within Meteor 1.3

In my Meteor 1.3.2.4 project, I tried utilizing the synchronous features of the request npm package. I initially followed the instructions provided in this guide article from Meteor and attempted to use Meteor.bindEnvironment. Here's the code: impor ...

Ways to bypass browser pop-up blockers when using the window.open function

I am displaying an HTML retrieved from the backend. printHtml(htmlContent) { var windowToPrint = window.open('', '_blank'); windowToPrint.document.write(htmlContent); setTimeout(function () { windowToPrint.document ...

Unable to "serialize" geoJSON information

While working with Leaflet JavaScript, I am attempting to retrieve data directly from GeoServer using an Ajax link. To display it nicely in a DataTables table, I need to convert it into JSON format as per DataTables instructions. However, I keep encounteri ...

Using d3 to showcase pictures sourced from a csv file

Having recently embarked on a journey to learn javascript, d3, and the polymer project, I am facing a challenge that I hope to get some guidance on. After successfully parsing a csv file containing image information and creating an array specifically for ...

Automate your workflow with Apps Script: Save time by appending a row and seamlessly including additional details to the

I currently have 2 server-side scripts that handle data from an html form. The first script saves user input to the last row available in my Google sheet, while the second script adds additional details to the newly created row. Although both scripts work ...

Issues with retrieving JSON data from Google Books API object

I've been working on retrieving data from the Google Books API and displaying the titles of the first 10 results on a web page. The site is successfully making the request, and I have a callback function that handles the results as shown below: funct ...

The specified project directory was not detected. Please restart Next.js in your updated directory

I am facing a challenge with running my NextJS web app on a VPS server with PM2 as the Process Management tool. Despite trying different approaches, I am unable to get it to run properly. I have a deploy.js file that successfully deploys my other NextJS an ...

Fill the next Thursday with JavaScript

I'm having trouble updating the date for the upcoming Thursday using JavaScript. The current script works fine until the end of the month, but if it's the 25th of August, the output will be "Next Thursday - 8/32/2022". I need a more intelligent s ...

"JQuery conflict arises due to compatibility issues between Yoast and bbPress

Following the recent update of Yoast to version 4.7, it appears that JQuery is experiencing conflicts and not running properly. I noticed that in version 2.3.5 of Yoast, JQuery runs fine and I see this code on the page: <script type='text/javascri ...