Executing "mounted" in VueJS SSR with Quasar: A step-by-step guide

In accordance with the documentation:

Given that there are no dynamic updates, only beforeCreate and created Vue lifecycle hooks will be triggered during SSR. This implies that any code within other lifecycle hooks like beforeMount or mounted will solely execute on the client side.

I'm finding it difficult to initiate this call. I have some functionalities that cannot run on the server. My assumption was that having "mounted" alone would suffice for it to invoke, but that doesn't seem to be the case.

To provide a bit of context, I am constructing a dropdown menu using foundation which works fine in standard Vue (non-SSR).

The structure of the file looks as follows:

<template>

<ul class="vertical menu accordion-menu" data-accordion-menu data-multi-open="false">
    <li v-for="i in htmlData.sidenav" :key="i.title">
        <router-link v-bind:to=i.href>{{ i.title }}</router-link>
        <ul class="menu vertical nested" v-if="i.sub1">
            <li v-for="j in i.sub1" :key="j.name">
                <router-link v-bind:to=j.href>{{ j.name }}</router-link>
                <ul class="menu vertical nested" v-if="j.sub2">
                    <li v-for="k in j.sub2" :key="k.name">
                        <router-link v-bind:to=k.href>{{ k.name }}</router-link>
                      </li>
                  </ul>
              </li>
          </ul>
      </li>
  </ul>
</div>


</template>


<script>
import SideNav from '../store/modules/sidenav'
import $ from 'jquery'

export default {
    name: 'sidenav',

    computed: {
        htmlData () {
            this.acc()
            return this.$store.state.sn.nav
        }
    },

    // Server-side only
    serverPrefetch () {
        this.$store.registerModule('sn',  SideNav)
        return this.getData()
    },

    // Client-side only
    mounted () {
        console.log('mt')
        const doesExist = !!this.$store.state.sn.nav
        this.$store.registerModule('sn', SideNav, { preserveState: true })

        if (!doesExist) {
            this.getData()
        }
    },

    destroyed () {
        this.$store.unregisterModule('sn')
        this.menu.destroy()
    },

    methods: {
        async getData () {
            return this.$store.dispatch('sn/snav')
        },

        acc () {
            this.$nextTick(function () {
                this.menu = new this.$foundation.AccordionMenu($('.accordion-menu'))
            })
        },
    }
}

While the sidenav successfully renders, it remains invisible to the client, resulting in the following error:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'AccordionMenu' of undefined

This discrepancy is evident because the menu actually renders, yet there is no record of "mt" in the console, although "pref" does log. This issue leads to various problems with page rendering (it fails without a hard refresh).

The content of the file under "boot/sidenav" is as follows:

// const SideNav = () => import('../layouts/SideNav.vue')
import SideNav from '../layouts/SideNav.vue'

export default async ({ Vue }) => {
    Vue.component('side-nav', SideNav)
}

Furthermore, the quasar.conf includes the following:

        boot: [
            'axios',
            'sidenav',
            'notemenu',
            {
                path: 'foundation',
                server: false
            },
            {
                path: 'osmd',
                server: false
            }
        ],

Neither the "foundation" nor the "osmd" can be viewed by the client. They both require the window object to function and hence cannot execute on the server. The situation becomes even more perplexing since "sidenav" does render and behaves as a reactive component.

Answer №1

Experience the lifecycle of components in action by using this example. In both server-side rendering and client-side rendering, only beforeCreate and created functions are called.

<template>
<div>Hello World</div>
</template>

<script>
export default {
name: "Test",
beforeCreate() {
 console.log('beforeCreate', process.env, this)
},
created() {
 console.log('created', process.env, this)
},
beforeMount() {
 console.log('created', process.env, this)
},
mounted() {
 console.log('mounted', process.env, this)
},
beforeUpdate() {
 console.log('beforeUpdate', process.env, this)
},
updated() {
 console.log('updated', process.env, this)
},
beforeDestroy() {
 console.log('beforeDestroy', process.env, this)
},
destroyed() {
 console.log('destroyed', process.env, this)
},
preFetch() {
 console.log('preFetch', process.env, this)
}
}
</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

Access the web location using jQuery's ajax functionality

I need help figuring out how to post data to my "mail.py" script without knowing the URL link. Both my jQuery AJAX code and JavaScript file are located in RKProjects/scripts_js/contactform.js The Python script I want to connect to is stored in RKProjects ...

What could be the reason for rowsAffected not returning an integer value?

Currently, I am working on executing the SQLite statement in an iOS application. To verify the count of affected records, I have implemented success and error callback methods. Upon receiving the results, although the variables are correctly defined, I en ...

What is the best way to change template variables that are set using :set?

Below is the code snippet I am currently working with in vue v3.2.33: <template v-for="route of routes" :key="route.name"> <li :set="open = false"> <div class="collapse" @click="open = ...

Getting the Mongoose Model using Express parameters is a simple process

Is it possible to dynamically fetch a mongoose model based on the req.params.model? Check out this example of a Schema const mongoose = require("mongoose"); const Schema = mongoose.Schema; const SmartSchema = new Schema({ SmartPriority: { type: Stri ...

Solving the error message: "Objects cannot be used as a React child (found: object with keys {})"

I am currently in the process of developing a full stack website that utilizes React, Express, Sequelize, and mySQL. The site is operational with features like registration and login implemented successfully. However, I encountered an issue when trying to ...

Learn how to easily copy the success result from an Ajax call to your clipboard

Is there a way to use an ajax method to retrieve data from a controller and display it in a JQuery Dialog Box? I want to add a button within the dialog box that allows the user to easily copy the data with a single click, instead of having to manually high ...

Enhancing functionality through the press of a button

I wrote a script that, upon button click, finds the closest location to your current position by searching through an array. It then locates the corresponding entry in another array and adds a number to that entry. However, I encountered a problem with app ...

Having trouble with installing Recharts through npm

When I try to install recharts using npm, I encounter the following error message in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! ...

Ways to segment into a proper array

I received the following object from an API and I am looking to convert it into an array using either JavaScript or C#. [ "1":"h1:first", "2":".content a > img", "3":"#content div p" ] I attempted converting it to a JSON object and using the spl ...

`Instant Messaging System using Asp.Net`

Looking for a way to send instant messages (similar to forum PMs) between users in my asp.net application. Like many others, I am using a webhosting service to host my site. After searching for a while, I have not been able to find a suitable solution th ...

What is the best way to incorporate a variable in the find() method to search for similar matches?

I've been working on a dictionary web application and now I'm in the process of developing a search engine. My goal is to allow users to enter part of a word and receive all similar matches. For instance, if they type "ava", they should get back ...

What is the best way to display HTML in this particular situation?

This is the function I am working on: public static monthDay(month: number): string { let day = new Date().getDay(); let year = new Date().getFullYear(); return day + ", " + year; } I am trying to add <span></span> tags around ...

Show the "Splash" picture, then switch to a newly uploaded image and show it for a set amount of time

I am in the process of developing an HTML/JavaScript page that will showcase a splash image (splash.jpg) until it gets replaced by another image file called latest.jpg. Once this latest.jpg is displayed, I want it to remain on the screen for 90 seconds bef ...

The issue arises when attempting to apply a filter to an array, as the variable returns as

After successfully using local state, I encountered an issue with Redux where the component returned undefined. How can I effectively compare two arrays and filter out users who are already in the current users array? import { FETCH_USERS_TO_ADD } from & ...

Ways to remove items from Vuex store by utilizing a dynamic path as payload for a mutation

I am looking to implement a mutation in Vuex that dynamically updates the state by specifying a path to the object from which I want to remove an element, along with the key of the element. Triggering the action deleteOption(path, key) { this.$store.d ...

Issues with ontimeupdate event not triggering in Chrome for HTML5 audio files

After creating an HTML5 audio element and setting a listener for when its time updates, I have run into an issue where the ontimeupdate function does not fire in Chrome, including Chrome on Android. The audio plays without any issues in other browsers. va ...

retrieving serialized object from an ajax request sent to the web server

As a newcomer to web development, I decided to create an ASP.NET project with a web API to test my skills. In the process, I crafted a controller and some JavaScript files as follows: Controller: namespace MyNamespace.Controllers { public c ...

A guide on retrieving the upload status of a file using an AJAX post request

Is there a way to retrieve the status of uploaded files when the user cancels the process while uploading multiple files using an ajax call? This is how I am currently making the ajax request to upload files: var request = $.ajax({ url: 'file ...

What is the process of combining two identical objects in Angular JS?

Is it possible to merge and sort two objects in Angular JS that have the same fields, notifications.fb and notifications.tw, based on their time field? ...

How disabling SSR is causing my styles to break in Nextjs

My Nextjs app is causing some issues with styling when I disable SSR to connect to Metamask using the window object. Specifically, the Navbar title style changes when SSR is disabled and the dev server is restarted: With SSR enabled: https://i.sstatic.net ...