I am trying to use a dynamic transition name for nuxt page transition like this belows
JavaScript
x
25
25
1
export default{
2
data() {
3
return {
4
prevHeight: 0,
5
transitionName: 'page'
6
};
7
},
8
transition: {
9
name: this.transitionName,
10
beforeLeave(el) {
11
this.prevHeight = getComputedStyle(el).height;
12
},
13
enter(el) {
14
const { height } = getComputedStyle(el);
15
el.style.height = this.prevHeight;
16
setTimeout(() => {
17
el.style.height = height;
18
}, 0);
19
},
20
afterEnter(el) {
21
el.style.height = 'auto';
22
}
23
}
24
}
25
this code will be mixined in all page components.
But I got two bugs here:
- the
prevHeight
attribute will not change when redirect to other pages I add a wather in it like thisnothing will print in the consoleJavaScript161watch: {
2'prevHeight'(height){
3console.log(height)
4}
5}
6
What else: I try to fix it by using a callback function instead of a object like this:
JavaScript
1
6
1
transition(){
2
return {
3
4
};
5
}
6
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
JavaScript
1
2
1
<nuxt/>
2
can be simply considered as
JavaScript
1
4
1
<transition>
2
<router-view/>
3
</transition>
4
so, everything is clear, modify the layouts/default.vue
JavaScript
1
44
44
1
<template>
2
<main>
3
<header>
4
Header
5
</header>
6
<transition
7
mode="out-in"
8
:name="transitionName"
9
@beforeLeave="beforeLeave"
10
@enter="enter"
11
@afterEnter="afterEnter">
12
<router-view/>
13
</transition>
14
<footer>
15
Footer
16
</footer>
17
</main>
18
</template>
19
<script type="text/javascript">
20
export default{
21
data() {
22
return {
23
prevHeight: 0,
24
transitionName: 'fade'
25
};
26
},
27
methods: {
28
beforeLeave(el) {
29
this.prevHeight = getComputedStyle(el).height;
30
},
31
enter(el) {
32
const { height } = getComputedStyle(el);
33
el.style.height = this.prevHeight;
34
setTimeout(() => {
35
el.style.height = height;
36
}, 0);
37
},
38
afterEnter(el) {
39
el.style.height = 'auto';
40
}
41
}
42
}
43
</script>
44
just like a SPA project