How to change routing parameters of Nuxt.js router without refreshing the page?
P粉131455722
P粉131455722 2023-11-05 14:05:53
0
2
567

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.

Attempt 1:

I tried usingkeep-aliveon the rootcomponent, but this only caches each page. It still remounts every time the route changes.

Attempt 2:

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?

P粉131455722
P粉131455722

reply all (2)
P粉550823577

To cache a rendered component, usekeep-aliveon thecomponent in the layout:

Demo 1

To cache only a specific page, usekeep-alive-props.includeand the component name (i.e. the path to the page):

Demo 2

    P粉518799557

    I'm 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:

    This gave me an idea to force a constant key to be assigned to the page by using

    .

    Now, the key will not be updated with each new route,

    pages/index.vueThe page will only be mounted once, and all subsequent routes will use the same page instance!

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!