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

Can a single component support multiple v-model bindings simultaneously?

Having a component used in two different places with an <input v-model="model" >, I face the challenge of watching this v-model in my component. The issue arises as the model changes - one place has model = array.val1 while the other has model = arra ...

extracting values from deeply nested JSON array in JavaScript

Is there a way to extract values from a deeply nested JSON array? I'm looking to retrieve all pairs of (nameValue and value) from the JSON provided below var json = [{ name: 'Firstgroup', elements: [{ ...

Different JQuery countdowns in an iteration using Django

I'm in the process of developing a sports app using Django. One of the key features I want to include is the ability to display a list of upcoming matches with a countdown timer for each match. Currently, I have managed to implement a single countdow ...

An issue arises when attempting to execute npm with React JS

I encountered an error after following the setup steps for a react configuration. Can anyone provide assistance? This is the content of the webpack.config.js file: var config = { entry: './main.js', output: { path:'/', ...

Based on the action taken, send specific data through AJAX - whether a form submission or a div click

There is a function called search, which can be triggered either by clicking on a div or submitting a form. When the div is clicked, the id of the div is sent as data in an AJAX call. However, if the form is submitted, I want to send the inputted data thr ...

What steps should I take to address both the issue of duplicate names and the malfunctioning fixtures?

There are issues with duplicate item names and the cache not updating immediately after running the script. Instead of fetching new data, it retrieves previous values from the last item shop sections. If the remove_duplicates function is not used, it displ ...

Is there an easier method to assign text to a modal-body using a specific classname?

Utilizing Bootstrap 5.1.3 alongside Pure Vanilla JavaScript, I have successfully been able to populate the .modal-body with content using the following code: function showBSModal(modalid, inputid) { var myModal = new bootstrap.Modal(document.getElement ...

Experience the convenience of Visual Studio Code's auto-completion feature for HTML tags even when working within an

My HTML file has a babel script embedded within it. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React tutorial</title> <script src="https://unpkg.com/react@16/umd/react.development.js" ...

Windows location does not change after an XMLHttpRequest is made

Here is my code that uses XMLHttpRequest: function SignUp() { signUpConnection = new XMLHttpRequest(); signUpConnection.onreadystatechange = processRegistration; signUpConnection.open('GET', 'index.php?registrarse=&username= ...

Exploring the possibilities of integrating vuex into Vue 3

In the past year, I dedicated time to learning Vue 2 and found it very enjoyable. However, I didn't proceed with a project at that time. Now, I have the opportunity to start a new project and would like to utilize Vue 3 along with the composition API, ...

New feature incorporated at the end of choices in MUI auto-suggest widget

Currently, I'm working on enhancing a category adder feature. Previously, I had limited the display of the "add category chip" to only appear for the no-options render scenario. However, I came across an issue where if there was a category like "softw ...

A helpful guide on incorporating data from one component into another component in Vue.js

Recently, I started working with Vue and I am facing a challenge in transferring an array from one component to another. The first component contains the following data that I need to pass on to the second component: const myArray = []; Both components a ...

Is there a way to dynamically modify a website's default viewport settings in a mobile browser?

When viewing a website in Landscape mode, everything looks good. However, switching to Portrait mode displays the message "Screen size not supported." I decided to test this on my desktop browser and discovered that adjusting the initial-scale:1 to initial ...

Harnessing the power of VUE.js: Exploring the versatility of V-bind with Array and

I've encountered an issue with an app I'm currently working on. In my project, I am utilizing Vue.js to create the front-end and attempting to apply two classes to a div within a v-for loop. The first class is bound with a filter that functions ...

Changing the application's state from within a child component using React and Flux

UPDATE It seems that my initial approach was completely off base. According to the accepted answer, a good starting point is the TodoMVC app built with React + Flux and available on GitHub. I am currently working on a small React + Flux application for ed ...

Changes in date format using jQuery datepicker

I am having trouble with the code below. Whenever I attempt to change the date, it switches from 15/5/2012 to 05/15/2012. <script> $(document).ready(function(){ $("#date").datepicker({ }); var myDate = new Date(); var month = myDa ...

Utilizing a dictionary for comparing with an API response in order to generate an array of unique objects by eliminating duplicates

I currently have a React component that utilizes a dictionary to compare against an API response for address state. The goal is to map only the states that are returned back as options in a dropdown. Below is the mapping function used to create an array o ...

When using ODataConventionModelBuilder in Breeze js, the AutoGeneratedKeyType will consistently be set to 'none'

I am working with a straightforward entityframework poco object public partial class Location: Entity { [Key] public int Id { get; set; } public string Description { get; set; } } The baseClass Entity is structured as below public abstract c ...

Several SVG Components failing to function properly or displaying differently than anticipated

I've encountered a puzzling issue that I just can't seem to solve. Here's the scenario: I'm working on a NextJS App and have 5 different SVGs. To utilize them, I created individual Icon components for each: import React from 'reac ...

Can you explain the distinction between the onclick(function(){}) and on('click',function(){}) functions in jQuery?

My goal is to dynamically load pages into a specific div using ajax. Here's my HTML code: <ul id="nav" class="nav" style="font-size:12px;"> <li><a href="#" id="m_blink">Tab1</a></li> <li><a href="#" id= ...