I’m looking for a way to disable the transition when:
-
I refresh the page, so that it only works when I switch between routes
-
And when I go to a particular section. For example, I am at the
Home
and I want to go to the#about
section on this route.
This is what I have inside <main>
:
<template>
<main>
<RouterView #="{ Component }">
<transition mode="out-in" name="fade">
<component :is="Component" :key="$route.fullPath" />
</transition>
</RouterView>
</main>
</template>
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
</script>
<style lang="scss">
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.2s ease;
}
</style>
Slight exception.
With this, let’s say I have 3 router-links: Search Recipes
, Home
, About
, where About
is a link that leads to the same URL as Home
, but with a hash: '#about'
. If I’m at Search Recipes
right now and I click on About
, I should be sent to Home
and its #about
section. In this case I want the transition to be applied. However, I don’t want the transition to be applied when I’m already on the Home
and I just want to slide to the #about
section. Hope you understand my explanation.
I use router-link for a link to the section:
<router-link
class="nav__menu-link"
:to="{ name: 'home', hash: '#about' }">
About</router-link
>
This is my router setup:
import { createRouter, createWebHistory } from 'vue-router';
import { routes } from '@/router/routes.js';
export const router = createRouter({
history: createWebHistory(),
routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
} else if (to.hash) {
return { el: to.hash, behavior: 'instant' };
} else {
return { top: 0 };
}
},
});
and my routes:
import ViewHome from '@/view/ViewHome.vue';
import ViewSearchRecipe from '@/view/ViewSearchRecipe.vue';
export const routes = [
{
path: '/',
name: 'home',
component: ViewHome,
},
{
path: '/searchRecipes/:name?',
name: 'searchRecipes',
component: ViewSearchRecipe,
},
];
Please, give a the solution and if possible, reproduce it with a similar to mine example.
2
Answers
Task #1 is done.
I had a mistake in the transition styles:
Instead it should be without '-from':
This way we won't have a transition on page reload.
You could create a data() called transitionName, with a default value:
and then assign it on your Transition tag:
You can then use beforeRouteEnter, beforeRouteUpdate and/or beforeRouteLeave inside each of your components, with conditions in order to change your transitionName via $emit.
Or you can create a global router.beforeEach in your main.js
with a Mixin (that is globally accessible and modifiable)
Also note that you can specify specific transitionName inside your router.
You can create a transition named "none" that doesn’t have any css or reset CSS.
Regarding the hash: ‘#about’ I’m not sure