vue spa项目中 window.location.hash 异常

为什么window.location.hash = this.$route.hash不起作用呢

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)
  }
},

下面两种情况都是会起作用的
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 = '#test')
  }
},

2.写在事件中

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

methods: {
  pushState(url) {
    window.location.hash = `#${url.split('#')[1]}`
  }
}
阅读 6.7k
4 个回答

你watch了hash,然后又改变hash,不会进入死循环吗

异步里面有this?

你先把this.$route.hash这个打印出来,应该是这个没值

我通过另一种方式实现了锚点的跳转

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

参考vue2.0中怎么做锚点定位

推荐问题
宣传栏