Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run function AFTER route fully rendered in Nuxt.js

Background:

I'm building an SSR website using Nuxt. I want to run a script to fix some typography issues (orphaned text in headers). I can't do this UNTIL AFTER the DOM is rendered. How can I implement this function once so it runs after each page's DOM is rendered? It can be either in the Router or in a Nuxt Layout, or elsewhere.

What I've tried:

  1. In my layout.vue, Mounted() only runs on the first load (as expected) and adding $nextTick doesn't seem to affect that. This is even true for generated static pages served from a real webserver.

  2. In my layout.vue, using Vue's Updated() never seems to fire. I assume this means Nuxt is getting in the way.

  3. Using app.router.afterEach() the function runs on each route change (including first load), but way before the DOM is rendered making it worthless.

  4. If I add Vue.nextTick() into the .afterEach() the function runs on the current page JUST BEFORE the route changes (you can see it flash) but DOES NOT run before that.

What works but seems dumb:

Putting the function in the Mounted() block on each page.

mounted: function(){
    this.$nextTick(function () {
    const tm = new TypeMate(undefined, { selector: 'h2, h3, p, li' });
    tm.apply();
     
    })
  },

But this seems like a bad idea especially as we add pages. What am I missing? Is there a smart way to do this? Nuxt's documentation is next to useless for some of this stuff.

like image 550
Bryce Howitson Avatar asked Apr 15 '19 19:04

Bryce Howitson


1 Answers

You can create mixin with mounted function. Lifecycle hooks from mixin will be merged with your lifecycle events and each will be run.

like image 161
Aldarund Avatar answered Sep 21 '22 08:09

Aldarund