I have a single page application using Nuxt.js (version 2.15.7) that needs to get two parameters from the URL. For example:
domain.com domain.com/chapter3 domain.com/chapter3/section5
All three addresses should render the same page found inpages/index.vue, I just want to be able to read$route.params.chapterNoand$route.params.sectionNowithout actually redirecting to another page.
I achieved this partially by editing mynuxt.config.jsfile like this:
router: { extendRoutes(routes, resolve) { routes.push({ name: 'chapter', path: '/chapter:chapterNo?', component: resolve(__dirname, 'pages/index.vue') }); routes.push({ name: 'section', path: '/chapter:chapterNo?/section:sectionNo?', component: resolve(__dirname, 'pages/index.vue') }); } },
The only problem is that this destroys the previous version ofpages/index.vueand remounts a new version every time it routes to a new chapter or section.mounted()is called every time the route changes, but I only need the page to be mounted once. It will animate on address changes, but with this setup the entire DOM is cleared and rebuilt, making it impossible to animate. Is there any routing configuration to get only these two parameters without re-rendering the entire page?
I tried removing thecomponentattribute of the configuration file, but this resulted in aPage not founderror.
I tried usingkeep-aliveon the rootcomponent, but this only caches each page. It still remounts every time the route changes.
I tried using therouter-extrasmodule with the define multiple parameters option, but it also remountspages/index.vueevery time the route changes. Here is my attempt, which produced the same problem:
{ path: '/chapter:chapterNo?/mission:missionNo?', }
Is there a way to change the route to get the parameters without remountingpages.index.vue?
To cache a rendered component, use component in the layout:
keep-aliveon theDemo 1
To cache only a specific page, use
keep-alive-props.includeand the component name (i.e. the path to the page):Demo 2
I'm using
This gave me an idea to force a constant key to be assigned to the page by usingin the default layout file. When looking at the Vue developer tools, I noticed that Nuxt creates a ## with a unique key for each chapter and section. New instance of #pages/index.vue:
Now, the key will not be updated with each new route,.pages/index.vue
The page will only be mounted once, and all subsequent routes will use the same page instance!