The script in (Nuxt.js/Vue.js) appears to only function once, becoming inactive after switching routes or refreshing the page

I'm currently in the process of transitioning my projects website to Vue.js with Nuxt.js integrated. I have been transferring all the files from the remote server to the local "static" folder.

Everything seems to be functioning properly, except for the JavaScript that runs when the page is initially loaded. Once I switch to a different page using the routes or refresh the current page, the JavaScript ceases to work.

For example, one of the pages on my projects website is:

This page allows users to drag an image onto other boxes, triggering class changes upon hover over any box with the image.

I moved the CSS to the local static folder successfully but encountered issues with the JavaScript. It only functions once and stops working after a route change or page refresh...

The script behaves as expected upon the initial load of the page; however, it fails to execute after a reload/change of route, resulting in no class transformations upon hovering over the boxes, etc... Despite working flawlessly the first time the page loads.

Upon researching this issue yesterday, I found responses to similar queries stating that the script is executed only once when the page is initially loaded. Hence, when there are route modifications or the page is refreshed, the script does not run again.

Some suggestions included adding the function intended for page load execution to the "created()" method within "export default" in the vue component.

In my scenario, I do not aim to execute something every time the page loads, but rather specific portions of the script triggered only by user interactions on the page...

Loading the script each time is unnecessary as the interactions may not occur, rendering the script redundant and increasing load times. Furthermore, incorporating the entire script into the "created" method would clutter the component.

Unfortunately, I did not find a concrete solution to this issue, only temporary fixes that produce unintended effects...

Here is the structure of my components (the following component is from ):

<template>
<div class="container">
    <div class="box">
        <div class="fill" draggable="true"></div>
    </div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>
</template>

<script>
export default {
    name: 'Drag',
    head: {
        link: [ { rel: 'stylesheet', type: 'text/css', href: 'css/drag.css'} ],
        script: [ { src: 'js/drag.js' } ]
    }
}
</script>

<style>

</style>

Do you have any suggestions to resolve this issue? Or any workarounds specific to my situation?

PS - Every time I close the tab and open a new one, the scripts work fine until the page is reloaded or the route is changed.

Answer №1

If you want to enhance the readability and reusability of your code, consider rewriting it in a Vue component style.

 <template>
  <div class="drag">
    <div
      v-for="n in range"
      :key="n"
      class="box"
      @dragenter="dragEnter"
      @dragover="dragOver"
      @dragleave="dragLeave"
      @drop="dragDrop"
    >
      <div
        v-if="n === 1"
        class="fill"
        draggable="true"
        @dragstart="dragStart"
        @dragend="dragEnd"
      />
    </div>
  </div>
</template>

<script>
export default {
  name: 'Drag',
  props: {
    range: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      dragged: ''
    }
  },
  methods: {
    dragEnter: function(e) {
      e.target.className += ' hovered'
    },

    dragOver: function(e) {
      e.preventDefault()
    },

    dragLeave: function(e) {
      e.target.className = 'box'
    },

    dragDrop: function(e) {
      e.target.className = 'box'
      e.target.appendChild(this.dragged)
    },

    dragStart: function(e) {
      e.target.className += ' ondrag'
      this.dragged = e.target
      setTimeout(() => (e.target.className = 'invisible'), 0)
    },

    dragEnd: function(e) {
      e.target.className = 'fill'
    }
  }
}
</script>

<style>
.drag {
  background-color: darksalmon;
  display: flex;
  justify-content: flex-start;
}

.box {
  background-color: white;
  width: 160px;
  height: 160px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  margin-right: 15px;
  border: 3px white solid;
}

.fill {
  background-image: url('http://source.unsplash.com/random/150x150');
  width: 150px;
  height: 150px;
  margin: 5px 5px;
  cursor: pointer;
}

.ondrag {
  border: solid #ccc 4px;
}

.invisible {
  display: none;
}

.hovered {
  background: #f4f4f4;
  border-style: dashed;
}
</style>

Answer №2

This solution may not be the most elegant, but it does address your specific request. By utilizing Nuxt, you can work around navigation issues by using traditional link elements instead of router-link or nuxt-link, which forces a complete page refresh.

It's important to note that Nuxt operates in universal mode, rendering the first page on the server and subsequent navigation as a single-page application. Your issue likely stems from event listeners being added during the initial visit but never removed.

To ensure proper functionality, utilize a link element for navigation to trigger a full page refresh with each click. Additionally, consider placing any necessary scripts at the bottom of the template to guarantee that all elements are present before execution:

<template>
  <div>
    <a href="/">
      Go Home
    </a>
    <div class="container">
      <div class="box">
        <div
          class="fill"
          draggable="true"
          dragstart="dragStart"
          dragend="dragEnd"
        />
      </div>
      <div class="box" />
      <div class="box" />
      <div class="box" />
      <div class="box" />
      <div class="box" />
    </div>
    <script src="js/drag.js" />
  </div>
</template>

<script>
export default {
  name: 'Drag',
  head: {
    link: [{ rel: 'stylesheet', type: 'text/css', href: 'css/drag.css' }]
  }
}
</script>

I have included a test link to "/" for verification purposes.

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

What could be causing this issue to not function properly in JavaScript?

Here is a JavaScript code snippet that I am working on: var inx=[2,3,4,5]; var valarray=[]; for (i=0; i<inx.length; i++) { valarray[i]==inx[i]; } for (i=0; i<inx.length; i++) { var posi=inx.indexOf(3); var valy=valarray[posi-1]+1; v ...

Exploring the benefits of looping with node.js require()

Currently, I have defined the required files as shown below. constantPath = './config/file/' fileAA = require(path.resolve(constantPath + 'A-A')), fileBB = require(path.resolve(constantPath + 'B-B')), fileCC = require(path.r ...

Uploading files using Ajax in the Laravel framework

I am attempting to utilize ajax to upload a file in Laravel. $("#stepbutton2").click(function(){ var uploadFile = document.getElementById("largeImage"); if( ""==uploadFile.value){ } else{ v ...

Tips for accessing arrayList data within a loop in JavaScript and displaying it in an HTML <c: forEach> tag

I have an array list stored inside a javascript code block. I am looking to extract this array list and iterate through it using the html tag <c:forEach>. How can I achieve this? Currently, I am able to display the array list using <h:outputText&g ...

JS: Initiating a new keypress operation

When I press the Tab key, I want it to do something different instead of its default action. Specifically, I have a text box selected and I would like it to add spaces (essentially making the textarea behave like a text editor). How can I trigger this type ...

Using jQuery to display checkbox text even when it is not directly adjacent to the checkbox

I'm struggling to display the checked value text as shown in the image without any refresh or click. Can anyone offer assistance? This is my PHP dynamic form: <div class="products-row"> <?php $tq=$conn->query("select * from os_tiffen ...

Transferring information from a service to an AngularJS controller

I have a service that retrieves data from a URL provided as a parameter, and it is functioning correctly. However, when attempting to pass this data to a controller's $scope in AngularJS, I am not receiving any data. var app = angular.module("Recib ...

Having trouble with using bootstrap-vue in my Vue.js application and encountering an error. Any suggestions on how to fix this issue?

This is the main.js file import { createApp } from 'vue' import App from './App.vue' import BootstrapVue from 'bootstrap-vue' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.c ...

Issue with Angular FormControl Pattern Validator failing to validate against regex pattern

My goal is to restrict a text input field to specific characters only. I am looking to allow: alphanumeric characters (a-z A-Z 0-9) 3 special characters (comma, dash, single quotation mark) : , - ' A few accented characters: à â ç è é ê î ô ...

NodeJS: Issue with Route is disrupting the functionality of the Restful API

Struggling to develop an API using Node.js and Express, encountering routing issues with express.Router(). Take a look at my code below: Server.js file contents: // Get necessary packages var express = require('express'); var app = express(); ...

Utilizing Django in conjunction with Vue to identify and address form validation errors

Utilizing a Django ModelForm with crispy forms for display on the template, upon completion of filling out the fields and clicking Submit, an email is triggered in the backend using Django's send_email functionality. However, the issue arises from th ...

Random sequencing of the commands

Whenever I call the Details function, it returns empty details because the function executes before retrieving data from the json file. What is the best way to fix this issue? app.controller('loginCtrl',function($scope,login){ $scope.user=login ...

Revise Script to Duplicate Alt Attribute onto Miniatures

I'm customizing a gallery plugin for a website that I am currently developing, aiming to add support for titles. The script I am using can be found here: DEMO: http://jquery.malsup.com/cycle/pager2.html CODE: All the functionalities are in place e ...

Router Express, parsing the body, and submitting a POST request

I have been experimenting with express.Router to organize my routes and testing post requests using Postman. I noticed that when I make a post request to /test without using router body-parser, everything works fine and I can view the body content. However ...

Do ES6 features get transpiled into ES5 when utilized in TypeScript?

After implementing ES6 features such as template strings, arrow functions, and destructuring in a TypeScript file, I compile the code to regular JavaScript... Does the TypeScript compiler also compile the ES6 syntax, or do I need to utilize another compil ...

One way to generate div elements based on the number in an input field when a button is clicked, but ensuring it only happens once

What I am attempting to achieve is: Retrieve data from a JSON file upon button click. Display the data in separate boxes, each one different for every element of the array. For instance, if the JSON provides 3 rows of data, there should be 3 distinct box ...

Having trouble displaying values from nested JSON in a datatable

Response from server : ["{\"CLIENT\":[{\"tranche\":\"1-4\",\"prix\":\"65.96\",\"currency\":\"E\"}],\"DISTRIBUTEUR\":[{\"tranche\":\"1-4\",\"prix\ ...

Tips for utilizing ng-checked and ng-disabled in conjunction with ng-repeat

I encountered a challenge with ng-repeat while incorporating ng-checked and ng-disable alongside it. <div ng-repeat="module in modulelist"> <input id="switch{{$index}}" ng-init="setState($index);" type="checkbox" ng-checked="switch.checked" ng-di ...

Navigating through images within my application

When setting images, I encounter an issue where the second image overlaps the first one instead of appearing separately. How can I ensure that each image is displayed in its own box? I have attempted to use a blob directly by returning imgUrl in the showI ...

Using caret range and package-lock.json to acquire the most recent non-disruptive versions

I understand the purpose of package-lock.json, but I'm unsure about how the caret range works after adding this file. Let's say I have a package called my-module and I want to automatically receive all new non-breaking versions without manually ...