How to change body styles in Vue Router?

Sometimes, we want to change body styles in Vue Router.

In this article, we’ll look at how to change body styles in Vue Router.

How to change body styles in Vue Router?

To change body styles in Vue Router, we can add a watcher for the $route object and then change the styles in the watcher.

For instance, we write

<script>
export default {
  //...
  watch: {
    $route: {
      handler(to, from) {
        const [body] = document.getElementsByTagName("body");
        if (from !== undefined) {
          body.classList.remove(`page-${from.name.toLowerCase()}`);
        }
        body.classList.add(`page-${from.name.toLowerCase()}`);
      },
      immediate: true,
      deep: true,
    },
  },
  //...
};
</script>

to add a watcher for the $route object.

We get the body element with getElementsByTagName.

Then we call body.classList.remove to remove the class if from isn’t undefined.

And then we call body.classList.add to add the class again.

We set immediate to true so the watcher runs immediately when the page loads.

And we set deep to true to run the watcher when any content in the $route object changes.

Conclusion

To change body styles in Vue Router, we can add a watcher for the $route object and then change the styles in the watcher.