I am trying to use a dynamic transition name for nuxt page transition like this belows
export default{
data() {
return {
prevHeight: 0,
transitionName: 'page'
};
},
transition: {
name: this.transitionName,
beforeLeave(el) {
this.prevHeight = getComputedStyle(el).height;
},
enter(el) {
const { height } = getComputedStyle(el);
el.style.height = this.prevHeight;
setTimeout(() => {
el.style.height = height;
}, 0);
},
afterEnter(el) {
el.style.height = 'auto';
}
}
}
this code will be mixined in all page components.
But I got two bugs here:
- the
prevHeightattribute will not change when redirect to other pages I add a wather in it like thisnothing will print in the consolewatch: { 'prevHeight'(height){ console.log(height) } }
What else: I try to fix it by using a callback function instead of a object like this:
transition(){
return {
...
};
}
but it won’t work.
How can I achieve this? I read the doucment (Nuxt transitions) but nothing help.
Thanks a lot!
Advertisement
Answer
After reading the resource code of nuxt, the
<nuxt/>
can be simply considered as
<transition>
<router-view/>
</transition>
so, everything is clear, modify the layouts/default.vue
<template>
<main>
<header>
Header
</header>
<transition
mode="out-in"
:name="transitionName"
@beforeLeave="beforeLeave"
@enter="enter"
@afterEnter="afterEnter">
<router-view/>
</transition>
<footer>
Footer
</footer>
</main>
</template>
<script type="text/javascript">
export default{
data() {
return {
prevHeight: 0,
transitionName: 'fade'
};
},
methods: {
beforeLeave(el) {
this.prevHeight = getComputedStyle(el).height;
},
enter(el) {
const { height } = getComputedStyle(el);
el.style.height = this.prevHeight;
setTimeout(() => {
el.style.height = height;
}, 0);
},
afterEnter(el) {
el.style.height = 'auto';
}
}
}
</script>
just like a SPA project
