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.chapterNo
and$route.params.sectionNo
without actually redirecting to another page.
I achieved this partially by editing mynuxt.config.js
file 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.vue
and 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 thecomponent
attribute of the configuration file, but this resulted in aPage not found
error.
I tried usingkeep-alive
on the root
component, but this only caches each page. It still remounts every time the route changes.
I tried using therouter-extras
module with the define multiple parameters option, but it also remountspages/index.vue
every 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-alive
on the
Demo 1
To cache only a specific page, use
keep-alive-props.include
and 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 using
in 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!