DEV Community

Cover image for Mounted and BeforeDestroy Hooks in Vue.js functional components.
Mikhail Panichev
Mikhail Panichev

Posted on

Mounted and BeforeDestroy Hooks in Vue.js functional components.

When you using Vue.js functional components you have nothing except render function and it's context with some parameters.

I always prefer to use functional component instead of a stateful component in my shared components library at work and it works fine when I don't need state. But sometimes I need mounted and beforeDestroy hooks in a stateless component.

The problem

Let's look at the example. We need a simple modal component that renders some overlay and block with passed children. Something like this:

export default {
  functional: true,
  render (h, context) {
    return (
      <div class="modal">
        <div class="modal__overlay" />
        <div class="modal__content">{context.children}</div>
      </div>
    );
  },
};

I didn't provide any styles but it should look like bootstrap modal. Now if the window has y scroll opened modal will be moving with page scroll. To create better UX we should disable scroll when modal is opened and enable it again when modal is closed. When using usual components you can do it in mounted and befoDestroy hooks:

export default {
  // ...
  mounted () {
    document.body.style.overflow = 'hidden';
  },
  beforeDestroy () {
    document.body.style.overflow = null;
  },
  // ...
};

But how to implement this logic without hooks? The answer is: using <transition> component with appear prop!

The solution

<transition> component has its own hooks for entering and leaving, so we can just wrap all our component in it and define hooks. The appear prop guarantees that our "mounted" hook will be fired when component mounts.

const mounted = () => {
  document.body.style.overflow = 'hidden';
};
const beforeDestroy = () => {
  document.body.style.overflow = null;
};

export default {
  functional: true,
  render (h, context) {
    return (
      <transition
        appear
        name="fade"
        onAfterEnter={mounted}
        onBeforeLeave={beforeDestroy}
      >
        <div class="modal">
          <div class="modal__overlay" />
          <div class="modal__content">{context.children}</div>
        </div>
      </transition>
    );
  },
};

That's it! Now we have some hooks in a functional component.

You can also improve your UI by implementing transition animations.

Photo by Suad Kamardeen on Unsplash

Top comments (0)