Skip to content
Advertisement

dynamic transition name for ssr-nuxt page transition

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:

  1. Cannot read property 'transitionName' of undefined Cannot read property 'transitionName' of undefined
  1. the prevHeight attribute will not change when redirect to other pages I add a wather in it like this
      watch: {
          'prevHeight'(height){
              console.log(height)
          }
      }
    
    nothing will print in the console

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement