Run function AFTER route fully rendered in Nuxt.js

前提是你 提交于 2021-01-27 08:15:33

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/55695816/run-function-after-route-fully-rendered-in-nuxt-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!