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 in pages/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 my nuxt.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 of pages/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 the component
attribute of the configuration file, but this resulted in a Page not found
error.
I tried using keep-alive
on the root <Nuxt>
component, but this only caches each page. It still remounts every time the route changes.
I tried using the router-extras
module with the define multiple parameters option, but it also remounts pages/index.vue
every time the route changes. Here is my attempt, which produced the same problem:
<router> { path: '/chapter:chapterNo?/mission:missionNo?', } </router>
Is there a way to change the route to get the parameters without remounting pages.index.vue
?
P粉5508235772023-11-06 00:41:58
To cache a rendered component, use keep-alive
on the
<Nuxt> component in the layout:
<Nuxt keep-alive />
To cache only a specific page, use keep-alive-props.include
and the component name (i.e. the path to the page):
<Nuxt keep-alive :keep-alive-props="{ include: 'pages/index.vue' }" />
P粉5187995572023-11-06 00:13:47
I'm using <Nuxt keep-alive />
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:
<Nuxt nuxt-child-key="doNotReMount"/>.
pages/index.vue The page will only be mounted once, and all subsequent routes will use the same page instance!