Jump to content
Search Community

Preserve Draggable Position through Vue keep-alive

SeanAye test
Moderator Tag

Recommended Posts

I am using a Draggable to create a smooth scrolling and snapping video feed (see attached post for context)

 

Everything is working great except the position of the Draggable is being reset after the page is navigated away from and back even though the component is being kept alive through Vue. This must have something to do with how vue serializes and stores components in memory. Is there a way to instantly reset the position of the draggable to what it was before?  I have tried the following but it does not update the value (see onActivated hook).

 

const state = reactive({
  snapHeight: 0,
  currentIndex: 0,
  mostRecentObseravtion: 0
})

const drag = ref<globalThis.Draggable[]|null>(null)

onActivated(() => {
  if (drag.value) {
    console.log({ drag: drag.value[0] })
    // Typescript complains this is a readonly value
    // drag.value[0].y = -state.currentIndex * state.snapHeight
    drag.value[0].update()

  }
})

onMounted(() => {
  // a parent node must have a #feed-page id to determine the scroll height
  state.snapHeight = document.querySelector('#feed-page')?.clientHeight || 0

  drag.value = Draggable.create('#scroller', {
    type: 'scroll',
    throwProps: true,
    allowNativeTouchScrolling: false,
    dragClickables: false,
    snap: (endValue) => {
      const curHeight = -state.currentIndex * state.snapHeight
      console.log({ endValue, curHeight, snapHeight: state.snapHeight })
      if (endValue < (curHeight)) { // scrolling values are negative/going down
        console.log('scroll down')
        return (state.currentIndex + 1) * state.snapHeight
      } else {
        console.log('scroll up')
        return (state.currentIndex - 1) * state.snapHeight
      }
    },
    inertia: true,
    onThrowComplete: () => {
      state.currentIndex = state.mostRecentObseravtion
    },
    maxDuration: 0.5,
    overshootTolerance: 0.5
  })
})

 

Link to comment
Share on other sites

I'm betting you'll need to save the value when you're unmounting it and then use that value when it's mounting again to store it. 

 

In terms of setting it again you don't set the value on the Draggable itself. You change the value of what the Draggable is affecting. So in this case you'd change #scroller's scroll position.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...