Window.location.hash exception in vue spa project

Why doesn"t window.location.hash = this.$route.hash work

mounted() {
  this.$route.hash && (window.location.hash = this.$route.hash)
  // setTimeout(() => {
  //   console.log(this.$route.hash)
  //   this.$route.hash && (window.location.hash = this.$route.hash)
  // }, 2000)
},
watch: {
  "$route.hash"() {
    setTimeout(() => {
      console.log(this.$route.hash)
      this.$route.hash && (window.location.hash = this.$route.hash)
    }, 5000)
    // this.$route.hash && (window.location.hash = this.$route.hash)
  }
},

the following two situations will work
1.hash

watch: {
  "$route.hash"() {
    setTimeout(() => {
      console.log(this.$route.hash)
      this.$route.hash && (window.location.hash = this.$route.hash)
    }, 5000)
    // this.$route.hash && (window.location.hash = "-sharptest")
  }
},

2. Write in the event

<template>
    <a @click="pushState(url)"></a>
</template>

methods: {
  pushState(url) {
    window.location.hash = `-sharp${url.split("-sharp")[1]}`
  }
}

will you watch the hash, and then change the hash, will not enter the endless loop?


Asynchronous has this?


you print out this.$route.hash first, it should have no value


I realized the jump of the anchor point in another way

goAnchor(selector) {
  const anchor = this.$el.querySelector(selector)
  document.documentElement.scrollTop = anchor.offsetTop
}

refer to vue2.0 how to do anchor positioning

Menu