滚动上的vuejs修复了边栏,

时间:2018-11-28 08:08:58

标签: vue.js javascript-events vuejs2 vue-router

 <div class="col-sm-4 my-orders-order-now">
    <div :class="{ fixed: fixedOrderPanel }">
      <FixedPannel />
    </div>

  </div>



data () {
  return {
    orders: [],
    loading: false,
    fixedOrderPanel: false
 }
},

mounted () {
   this.getJokes()
   if (window !== undefined && window.addEventListener) {
    window.addEventListener('scroll',() => this.handleScroll(window.scrollY));
  }

},

 destroyed: function () { //Not working

 console.log('Afore')
    if (window !== undefined && window.removeEventListener) {
         window.removeEventListener('scroll', 
              ()=>this.handleScroll(window.scrollY));

    }
},

 methods: {
   handleScroll: function(scrolled){
   console.log('scrolling')
    if (scrolled > 160) {
        this.fixedOrderPanel = true
    } else {
        this.fixedOrderPanel = false
    }

},

}

销毁/组件或路由更改vuejs后,滚动侦听器的

window.removeEventListener仍然完好无损。每当更改路线或组件时,window.removeEventListener都不起作用,即使我同时尝试了beforeDestroy()和销毁方法来删除滚动事件侦听器

1 个答案:

答案 0 :(得分:-1)

<div class="col-sm-4 my-orders-order-now">
   <div :class="{ fixed: fixedOrderPanel }">
     <FixedPannel />
   </div>

</div>  


components: {
    FixedPannel
}, 

mounted () {
    this.getJokes()
    document.addEventListener('scroll',  this.handleScroll);
  },

 destroyed: function () {
    document.removeEventListener('scroll', this.handleScroll);

 },

 methods: {

    handleScroll: function(){
        const checkWindow = window !== undefined && window.scrollY;

        if (checkWindow && window.scrollY > 160) {
           this.fixedOrderPanel = true
        } else {
           this.fixedOrderPanel = false
       }

     const scrollFix = (scrolled) => {
        if (scrolled > 160) {

           this.fixedOrderPanel = true
         } else {
           this.fixedOrderPanel = false
        }
    }

    }
}

<style>
.fixed{
  position: fixed;
  top: 0px;
  padding: 1%;
 }

</style>