shshaw / Splitting

JavaScript microlibrary to split an element by words, characters, children and more, populated with CSS variables!
https://splitting.js.org
MIT License
1.66k stars 68 forks source link

nuxt / ssr workaround #65

Open flowen opened 3 years ago

flowen commented 3 years ago

yo @shshaw & @notoriousb1t just wanted to share my fugly workaround for anyone else in nuxt:

html:

<template>
   <h1 class="title" v-html="title" />
</template

computed:

  computed: {
    title: function() {
      const text = `split me baby`;

      if (typeof window !== `undefined` || typeof document !== `undefined`) {
        const Splitting = require("splitting");
        return Splitting.html({ content: text, by: "chars" });
      }

      return null;
    }
  },

nuxt.config.js:

  css: ["splitting/dist/splitting.css"],
  plugins: [{ src: "~/plugins/splitting.client.js", ssr: false }],
}

splitting.client.js:

import Vue from "vue";
import Splitting from "splitting";

Vue.use(Splitting);

last edit with a tip: If you want to style this make sure you've got no scoped attribute

flowen commented 3 years ago

You can put the above in a mixin function and have text as parameter.

also figured you can do it as easy as this:

<template>
    <h1 data-splitting="chars">Split me baby</h1>
</template>

  mounted() {
    if (typeof window !== `undefined` || typeof document !== `undefined`) {
      const Splitting = require("splitting");
      Splitting();
    }
  },

The benefit is, that with JS disabled, the title will still show. With the previous method, it won't. It does give a warning if you're animating charsMismatching childNodes vs. VNodes:. So depending on what you do, it can be a dealbreaker.

If someone knows how to fix showing the title in #1 case or knows how to fix the warning, please let me know 🙏

P-at commented 3 years ago

If someone knows how to fix showing the title in #1 case or knows how to fix the warning, please let me know 🙏

Wrapping it in a <client-only> component should fix the warning.

craigrileyuk commented 1 year ago

If you're running Nuxt with Vue 3, we've just created a lite adaptation of Splitting designed for Vue 3 which is fully SSR compatible (that's why we made it)

https://www.npmjs.com/package/vue3-splitting