Issue with Vue.js 2.0 transition not triggering on changing routes dynamically

I've encountered an issue where transitions are not firing on dynamic routes with parameters. For example, when navigating from /chapter/1 to /chapter/2, no transition occurs. However, when going from /chapter/1 to /profile/1, a transition does occur!

Here is the snippet from the main.js file:

require('normalize.css')

import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
import Panel from './components/Panel'
import Profile from './components/Profile'

window.bus = new Vue()

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
     { path: '/', redirect: '/chapter/1' },
     { name:'chapter', path: '/chapter/:id', component: Panel},
     { name:'profile', path: '/profile/:id', component: Profile}
  ]
})

new Vue({
  router,
  el: '#app',
  render: h => h(App)
})

And here is the template code from App.vue:

<template>
  <div id="app">

    <transition name="fade" mode="out-in">
      <router-view></router-view>
    </transition>

    <div class="controls">
      <router-link :to="{ name: 'chapter', params: { id: Math.max(1, parseInt($route.params.id) - 1) }}">
        Prev
      </router-link>
      <router-link :to="{ name: 'chapter', params: { id: parseInt($route.params.id) + 1 }}">
        Next
      </router-link>
    </div>
  </div>
</template>

I suspect that vue-router may not be destroying the parent component, causing the transition issue. I tried this configuration on the vue-router examples pack and experienced the same behavior.


Referencing the documentation, it states:

One thing to note when using routes with params is that when the user navigates from /user/foo to /user/bar, the same component instance will be reused. Since both routes render the same component, this is more efficient than destroying the old instance and then creating a new one. However, this also means that the lifecycle hooks of the component will not be called.

To react to params changes in the same component, you can simply watch the $route object


Do you think I should raise this as an issue?

Thank you for your assistance!

Answer №1

Take a look at this working example: https://jsfiddle.net/mani04/dLnz4rbL/

I tried using the technique outlined in the documentation under Transitioning Between Elements.

In my fiddle demo, which is based on the code provided in your question, I incorporated a transition wrapper within the component, like shown below:

<transition name="fade" mode="out-in">
    <div class="page-contents" :key="$route.params.id">
        This is my chapter component. Page: {{parseInt($route.params.id)}}
    </div>
</transition>

The documentation indicates that we need to assign a key to ensure they are seen as different elements by Vue.js. Therefore, I used your chapter ID as the key.

I'm not sure if this is a workaround or a proper solution since I transitioned from Angular2 to Vue just 2 weeks ago. Until a better solution is suggested, you could try this approach for achieving transitions with dynamic routes.

As for raising this as an issue on the github page of vue-router, it's uncertain if this warrants attention or fixing. However, bringing it to their notice would be beneficial. The fix might involve avoiding reusing components, which is also not ideal. It's a tough decision for them. Nonetheless, the discussion should be valuable! If you do decide to create an issue, please share the link here :-)

Answer №2

Dealing with the same issue led me to try out @Mani's solution, which worked well for me too. However, the concept of utilizing two <transition>s doesn't sit right with me.

Instead, I decided to place the key in the <router-view> element. Surprisingly, this alternative approach also did the trick! For a demonstration, you can check out this working example: https://codepen.io/widyakumara/details/owVYrW/

I'm not entirely certain if this method aligns with the recommended practices in Vue development, as I'm relatively new to using vue myself.

By the way, just to provide context, my setup involves Vue 2.4.1 and Vue Router 2.7.0.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating regex to detect the presence of Donorbox EmbedForm in a web page

I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...

Unable to establish SocketIO callback from client to server resulting in a null object instead

I'm encountering an unusual issue with SocketIO. On the server-side, I am using the emit() method like this: $s.sockets.emit(scope, {some: datas}, function(feedback) { console.log('received callback'); } ) ...

Unable to focus on the same DOM element multiple times - Vue.js

Apologies for any syntax errors, although the code is functioning perfectly. There may have been a mistake during the copying process. Situation: I am facing an issue with a component called 'dropdown', which is repeated three times using v-for= ...

`On mobile devices, the Bootstrap button no longer displays focus changes once clicked.`

When clicking a primary bootstrap button, it changes its background color to blue on mobile devices. https://i.sstatic.net/VNPDP.jpg For example, the first button appears normal and the second one turns blue after clicking. However, this background effec ...

Tips for ensuring text remains within a div container and wraps to the next line when reaching the edge

Currently, I am working on a flash card application using Angular. Users can input text in a text box, and the text will be displayed on a flash card below it. However, I have encountered an issue where if the user types a lot of text, it overflows and mov ...

Radio buttons with multiple levels

Looking to implement a unique two-level radio button feature for a specific option only. Currently, I have written a logic that will display additional radio buttons under the 'Spring' option. However, the issue is that when it's selected, t ...

Issues with jQuery slide operation

I'm facing an issue with jQuery and I can't figure out where it's coming from. Here is the error message that keeps showing up in the console: Uncaught TypeError: Object [object Object] has no method 'getElement' script_16.js:46Un ...

Tips for encoding ParsedUrlQuery into a URL-friendly format

Switching from vanilla React to NextJS has brought about some changes for me. In the past, I used to access my URL query parameters (the segment after the ? in the URL) using the useSearchParams hook provided by react-router, which returned a URLSearchPara ...

Vue JS is unable to interpret CSS codes within components

Currently, I am working on a project using Vue.js in combination with Laravel. However, I encountered a problem when trying to execute the npm run watch command. Vue.js is throwing the following error and preventing the project from being built: ERROR in ...

Xap or js Silverlight media player

Currently developing a Silverlight video player, I stumbled upon the JW Player for inspiration. I know that Silverlight apps are typically contained within .xap files, but JW Player utilizes JavaScript scripts to implement Silverlight logic. Can you plea ...

Issue with Chart.js V3.20: Struggling to Filter Legend Labels

Building a dynamic line chart using Chart.js with the capability of up to 19 datasets. The issue arises when there are less than 19 datasets, as the legend still displays for these unused datasets. Previously, a function was used in Chart.js 2.6.0 options ...

Implementing Material UI datetime-local feature with no minute selection

Is there a way to hide minutes in a TextField with type = datetime-local? <TextField label="From" type="datetime-local" InputLabelProps={{ shrink: true, }} /> This is how it appears on my end: screenshot ...

What is the best approach for sending mapbox coordinates to a higher-level class in a react application?

As a beginner in learning React, I'm currently working on setting a map marker with a click event on a Mapbox GL map. The challenge I'm facing is passing the lngLat object back up to the parent component. Can someone guide me on how to achieve th ...

Why does my JavaScript only trigger my web service request when I set a breakpoint?

Can you help me understand why my JavaScript code only calls my webservice when I set a breakpoint on the line ].getJSON, but not if I remove the breakpoint? $(function () { $("#" + @Model.BidObjectId).submit(function () { ale ...

Issue in Next.js 13: Byte index exceeds limits when running 'npm run dev' command

When attempting to install Next.js 13.4.12, I utilized the command npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385b4a5d594c5d15565d404c1559484878090b160c1609">[email protected]</a>. The installation process ...

Jquery unresponsive in AJAX form output presentation

I recently delved into the world of jquery and AJAX, and while I grasp most concepts, I'm struggling with a small code snippet. On my webpage, there is a summary of articles. Clicking on an article name triggers a popup window with detailed informati ...

How can I create an HTML select dropdown menu with a maximum height of 100% and a dynamic size?

The dropdown menu I created using an HTML select tag contains a total of 152 options. However, the large number of options causes some of them to be out of view on most monitors when the size is set to 152. I attempted to limit the number of displayed opti ...

Using onChange input causes the component to re-render multiple times

As I delve into learning React, I've encountered some challenges. Despite thinking that I grasped the concept of controlled components, it appears that there's a misunderstanding on my end. The issue arises after an onChange event where I notice ...

The URL type "npm:" is not supported in this context. Please specify a valid URL or resource

After running vue create my-project with Vue CLI, I encountered an error: npm ERR! code EUNSUPPORTEDPROTOCOL npm ERR! Unsupported URL Type "npm:": npm:vue-loader@^16.0.0-beta.3 npm ERR! A complete log of this run can be found in: npm ERR! /h ...

Opening a Bootstrap Modal in React without relying on npm react-bootstrap

I've been trying to create a Modal in React.js using Bootstrap5, but I'm unable to use npm react-bootstrap for various reasons. I attempted an approach where I utilized state to set Modal classes with a button, which worked well with my NavBar, b ...