locomotivemtl / locomotive-scroll

🛤 Detection of elements in viewport & smooth scrolling with parallax.
https://locomotivemtl.github.io/locomotive-scroll
MIT License
7.53k stars 1.11k forks source link

Locomotive Scroll v5 + Nuxt 3 Config? #560

Open kieranmansfield opened 3 weeks ago

kieranmansfield commented 3 weeks ago

Hey, What's the best way of implementing Locomotive scroll in Nuxt 3?

The general consensus is to add it as a plugin. I've tried to get it working it want to play nice with Locomotive Scroll.

Does anyone have an examples of how to get this working?

~/plugins/locomotiveScroll.client.js

import LocomotiveScroll from 'locomotive-scroll'

const locomotiveScroll = new LocomotiveScroll()

function raf(time) {
  locomotiveScroll.raf(time)
  requestAnimationFrame(raf)
}

requestAnimationFrame(raf)

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.provide('locomotiveScroll', locomotiveScroll)
})
pieterjanmaes commented 3 weeks ago

Hi,

I replied a few day's ago on an other related issue, this is how I use Locomotive scroll in Nuxt 3 => https://github.com/locomotivemtl/locomotive-scroll/issues/502#issuecomment-2136681236

Not sure if this is the 'correct' way to implement, ...

kieranmansfield commented 3 weeks ago

I tried this the other day and it didn't work for me, however I've just had another go and it worked like a treat. No idea why it was playing up before. Thank you!

kieranmansfield commented 3 weeks ago

@pieterjanmaes How do I actually implement something like Scroll to top?

<script setup>
const { $lenis } = useNuxtApp()

function scrollToTop() {
  $lenis.scrollTo(0)
}
</script>

<template>
      <Button @click="scrollToTop()">Back To Top</Button>
</template>

I've added Locomotive Scroll to useNuxtApp(), it doesn't seem to do anything.

  return {
    provide: {
      locomotiveScroll: locomotiveScroll,
    },
  }

Where am I going wrong with this?

pieterjanmaes commented 2 weeks ago

@kieranmansfield, i would do it like this:

https://scroll.locomotive.ca/docs/#/attributes?id=data-scroll-to-href

Add an id to the top of your page:

<button  data-scroll-to data-scroll-to-href="#top" data-scroll-to-offset="10">
   {{ buttonText }}
</button>

Or you could create a hook in the plugin:

nuxtApp.hook('locomotive:scrolltotop', () => {
    // locomotive logic
});

And then do something like this:

const nuxtApp = useNuxtApp();
nuxtApp.callHook('locomotive:scrolltotop');

I didn't test the code, just some suggestions :-)