问题
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:
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.In my
layout.vue
, using Vue'sUpdated()
never seems to fire. I assume this means Nuxt is getting in the way.Using
app.router.afterEach()
the function runs on each route change (including first load), but way before the DOM is rendered making it worthless.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