Restarting a JavaScript function upon switching views in Vue.js

I am new to working with Vue.js and I have a Laravel app that utilizes it. One issue I am facing is that when the homepage is loading, all elements like owl carousel and rev slider are initialized. However, if I navigate to other routes such as contact or about, then return to the homepage, the sliders and other JavaScript elements do not load.

routes.js
import VueRouter from 'vue-router';
import Home from './components/views/Home.vue';
import About from './components/views/About.vue';
import Contact from './components/views/Contact.vue';


let routes = [
    { path: '/', component: Home },
    { path: '/about', component: About },
    { path: '/contact', component: Contact},
];

export default new VueRouter({
    routes,
    linkActiveClass: 'active'
});

and app.js

import router from './routes';

import './components';

const app = new Vue({
    el: '#app',
    router
});

Is there a way to ensure that functions to initialize carousels and other elements run each time I change views?

Answer №1

If you want to include custom JavaScript for each component when it is mounted, you can use the mounted hook.

<script>
    export default {
        mounted () {

        }
    }
</script>

Answer №2

For those still searching for a solution, here is how I achieved it. Simply wrap the <route-view/> in a <transition> element which can be styled using CSS. Trigger a method on enter to execute the desired function. This will ensure that the function is called as soon as the component is loaded in the DOM during every route change.

<transition name="slide" v-on:enter="reInitJS">
   <router-view></router-view>
</transition>

<script>
// Import the required function
import {init} from './main';
export default {
  name: 'App', 
  methods: {
    reInitJS(){
      // Call the function
      init(); 
    }
  }
}
</script>

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

Proper method for calling a function within a specific scope

I am utilizing user-contributed modules that I aim to avoid editing in order to make upgrades easier. My goal is to enable users to browse for a CSV file on the local filesystem, parse it, and display it in a dynamic table. For this task, I am using PapaP ...

What are some solutions for resolving JavaScript's 'undefined' error?

(function(window) { var johnGreeter = {}; johnGreeter.name = "John"; var greeting = "Hello "; johnGreeter.sayHello = function() { console.log(greeting + johnGreeter.name); } window.johnGreeter = johnGreeter; })(window); // <!DOCTYPE html ...

When running the command `npm start`, an error message is generated

Hey everyone, I've been trying to learn some basic AngularJS 2.0 skills through a tutorial. Unfortunately, when I tried running the command npm run start, it didn't work as expected. I'm currently using Git Bash on Windows 10 OS. If you hav ...

Add new data to an existing array in Angular 7 without overwriting it

After clicking a button, I'm retrieving data from the WordPress API: <a (click)="initGetComments()">Get comments</a> This is the code snippet: export class AppComponent { commentsResults: CommentsItem[] = []; ...

The error message "Invalid Data Type: Not an Array - google charts" was encountered

I am struggling with an ajax call that I have set up. The issue arises when passing an array from the backend to the frontend. Upon checking the data through an alert on the frontend, everything seems fine. However, Google charts raises an error stating th ...

Issue encountered in AngularJS: struggling to store the localStorage item in the scope variable

I've been trying to save the values from window.localStorage.getItem('job_id.done_tasks') into a $scope variable, but I'm encountering difficulties. Can you please review my code? $scope.done_tasks = {}; $scope.done_tasks = window.loca ...

Checking for the existence of data in a MySQL table using Node.js resulted in an error message: "TypeError: res.send is

I am currently attempting to verify the existence of data in a mysql table. Upon doing so, I encountered an error indicating TypeError: res.send is not a function. The mysql table contains ample data with three columns, each specified as varchar(45), alon ...

Troubleshooting: Why is the Vue search feature in v-data-table not functioning properly

My issue involves using computed values to populate my v-data-table, and I am struggling to resolve the search functionality. Additionally, I would like to re-enable column sorting if possible. Below is the code for my v-Data-Table: <v-data-table ...

What is the process for reporting a security vulnerability in an npm package if you are the maintainer and publisher?

If I discover a security flaw in my published packages, how can I indicate which versions are vulnerable so that users running `npm audit` will be alerted? ...

Taking out the modal element from the document object model, causing the animation

I am currently working on a project using Next.js, Typescript, and Tailwind CSS. Within this project, I have implemented a modal component with some animations. However, I encountered an issue where the modal does not get removed from the DOM when closed, ...

"When using `app.use(express.static`, it appears that the functionality is not working properly when the app is a sub

I attempted to implement something similar to this: var main = express(); main.use(express.static(path.resolve('./asset'))); main.route('someroute', someHandle); var app = express(); app.use(express.static(path.resolve('./asset&ap ...

What steps can I take to personalize Material UI within a React application?

As someone who is new to this UI framework and React, I have been tasked with developing an application that requires more design patterns. I specifically chose a framework that does not depend on jQuery code. However, I am facing challenges when it comes ...

What could be causing my Vue code to behave differently than anticipated?

There are a pair of components within the div. When both components are rendered together, clicking the button switches properly. However, when only one component is rendered, the switch behaves abnormally. Below is the code snippet: Base.vue <templa ...

Stopping a Bootstrap Modal Closure When Validation Errors are Present

I'm dealing with a bootstrap model within a .NET MVC5 app. Although my client-side validation is functioning properly (using jquery unobtrusive in MVC), I have encountered an issue where the modal keeps closing even when there are errors present. How ...

Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). ...

SpineJS combined with Express

Are there any recommended tutorials or case studies showcasing the integration of SpineJS and Express in applications? I have experimented with both technologies, but am currently facing some challenges. My backend is set up to run Express by using coffee ...

Disabling a button based on the result of a database query

Is there a way to dynamically enable or disable a button based on the result of a database query in JavaScript? I have managed to display an error message (with id="error") depending on the result, but toggling the button (with id="generate") doesn't ...

How can I modify the appearance of the bootstrap scrollbar with scrollspy?

I'm struggling to modify the color of the scrollbar in Bootstrap scrollspy despite having a functional scrollbar. Here is an example of my code: HTML: <body> <div class="container, scrollbar" id="myScrollspy"> <div class=" ...

Is there a possibility of encountering an endless update loop within a component's render function?

Hello! I am a beginner in Vue.js and I have encountered an issue with my function. Instead of increasing my variable to 1 as expected, it is increasing it to a random number every time. The console is displaying the following error message: "You may hav ...

Using HTML and CSS to stack a DIV on top of another using z-index

I have 3 main layers on my website: 1) The main view with elements inside (#views in jsbin) - BOTTOM LAYER 2) An overlay (with a white background opacity of .8 #overlay in jsbin) - MIDDLE LAYER 3) A context menu (#contextmenu in jsbin) - TOP LAYER Wh ...