Having mounted() only run once on a component Vue.js Having mounted() only run once on a component Vue.js vue.js vue.js

Having mounted() only run once on a component Vue.js


You could wrap your components within a keep-alive element ..

<keep-alive>    <Element v-if="this.mode === 'mode'"/>    <OtherElement v-else /></keep-alive>


Using v-if, re-renders components every time the this.mode changes. Vue stores them in virtual DOM, but re-renders them if you use v-if.

If you have access to code for these components, consider using prop for v-show and watching it, in optional combination with emitso you can communicate between parent and child components, and set flag if you need it in child and in parent component if child component loads animation initially, to avoid loading it all over again.

This would be one of the child components:

<template>    <div v-show="mode === 'themode'">    </div></template><script>    export default {        props: {            mode: {                type: Boolean,                required: true,                twoWay: true            },        },        data()  {            return {                animationLoaded : false,            }        },        mounted(){        },         watch: {           'mode' : function(){            if(this.mode === 'mode' && this.animationLoaded === false){                //load animation and set flag to true, to avoid loading it again.                 this.animationLoaded = true;                 this.$root.$emit('component-name:animation-loaded');            }          }        },

...

And putting child in parent component:

  <child-component :mode.sync="mode"></child-component>


If created() doesn't do the job, you should try to do a simple check in the parent element if this.mode was switched on and off before, save the result as a variable and pass that to the mounted hook and only run the animation if the mode wasn't switched before.