关于vue.js:vue中在浏览器重新刷新页面吸顶效果失效

4次阅读

共计 1595 个字符,预计需要花费 4 分钟才能阅读完成。

问题:第一次加载我的项目的时候是能够失常显示吸顶成果的,然而从新刷新页面的时候就没有了

 created() {this.getDestruction()
      this.watchScroll()
      window.addEventListener("scroll", this.watchScroll);
  },
  async mounted() {await this.getMarket();
    // console.log('this.turnover',this.burn)
    this.drawLine();
    // 事件监听滚动条
  },
   destroyed() {
    // 移除事件监听
    window.removeEventListener("scroll", this.watchScroll);
    window.removeEventListener("scroll", this.handleClick);
  },
  methods: {watchScroll() {
      // 滚动的间隔
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      // 容器的高度
      var offsetTop = document.querySelector("#headtitle_bg").offsetHeight;
      //  滚动的间隔如果大于了元素到顶部的间隔时,实现吸顶成果
      if (scrollTop > offsetTop) {this.navBarFixed = true;} else {this.navBarFixed = false;}
    },
  }

吸顶之前

吸顶成果隐没

起因:获取不到 #headtitle_bg 节点
解决办法:应用 nextTick()办法,是将回调函数提早在下一次 dom 更新数据后调用,简略的了解是:当数据更新了,在 dom 中渲染后,主动执行该函数,Vue.nextTick()回调函数中的执行的应该是会对 DOM 进行操作。

批改后的代码

created() {// console.log(this.$refs.To_Repurchase_VNC)
    // this.getMarket()
    this.getDestruction()
    this.$nextTick(() => {this.watchScroll()
      window.addEventListener("scroll", this.watchScroll);
    })
  },
  async mounted() {// console.log(this.$refs.To_Repurchase_VNC)
    await this.getMarket();
    // console.log('this.turnover',this.burn)
    this.drawLine();
    // 事件监听滚动条
  },
   destroyed() {
    // 移除事件监听
    window.removeEventListener("scroll", this.watchScroll);
    window.removeEventListener("scroll", this.handleClick);
  },
  methods: {watchScroll() {
      // 滚动的间隔
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      // 容器的高度
      var offsetTop = document.querySelector("#headtitle_bg").offsetHeight;
      //  滚动的间隔如果大于了元素到顶部的间隔时,实现吸顶成果
      if (scrollTop > offsetTop) {this.navBarFixed = true;} else {this.navBarFixed = false;}
    },
}
正文完
 0