Vue 3 和 Window 对象反应性

问题描述 投票:0回答:1

我遇到了无法解决的问题,所以我需要一些帮助!

问题

我想听听

location.href
值的变化。

如何检测

window.location
对象的变化?

我需要创建一个可组合项,根据 SPA 的 href 更改更新一些值。

我得到了这样的东西:

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
}

没有人在工作:(

如何获得反应性

window
对象?或者至少是一个反应性的
href
??

谢谢!

vue.js window reactive vue-reactivity composable
1个回答
0
投票

Vue 的反应系统不会像您尝试的那样接收对 window.location 或 window.location.href 的更改。

你可以使用 Vue Router,你可以观察

$route
对象的变化:

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
    }
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.