Search code examples
vue.jswindowreactivevue-reactivitycomposable

Vue 3 and Window object reactivity


I'm facing an issue I'm not able to solve, so I need some help!

Problem

I would like to listen up changes on location.href value.

How could I detect changes in window.location object?

I need to create a composable that updates some values depending on href changes of my SPA.

I got something like this:

export default function useNavigationList () {
  const currentLocation = ref(window.location) // try 1
  const currentHref = ref(window.location.href) // try 2
  const toRefLocation = toRef(window, 'location') // try 3
  const toRefhRef= toRef(window.location, 'href') // try 4

  watch(currentLocation, () => console.log(currentLocation.value)) // Not working

  watch(currentHref, () => console.log(currentHref.value)) // Not working

  watch(toRefLocation , () => console.log(currentLocation.value), { deep: true }) // Not working

  watch(toRefhRef, () => console.log(toRefhRef.value)) // Not working
}

No one is working :(

How could I get a reactive window object? Or at least, a reactive href??

Thanks!


Solution

  • Vue's reactivity system won't pick up changes to window.location or window.location.href as you've tried to do.

    You could use Vue Router, you can watch the $route object for changes:

    import { ref, watch } from 'vue'
    import { useRoute } from 'vue-router'
    
    export default function useNavigationList() {
      const currentLocation = ref(window.location) // try 1
      const currentHref = ref(window.location.href) // try 2
      const toRefLocation = ref(window, 'location') // try 3
      const toRefhRef = ref(window.location, 'href') // try 4
    
      const route = useRoute()
    
      watch(
        () => route.fullPath,
        (newPath, oldPath) => {
          console.log('Route changed:', newPath)
    
          currentLocation.value = window.location
          currentHref.value = window.location.href
        }
      )
    }