Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

html - VueJS: How to dynamically change a CSS class after a scroll position

I am creating a webapp with vueJs and bootstrap. I want to change CSS class of an element after a particular amount of scroll, Is there some vue way of doing it.

I want something like following:

<div :class="{classA: scrollPosition < 100, classB: scrollPosition > 100}">
</div>

One option I found is by using vue-scroll, which seems promising, but not working.

Is there some other native way as well to achive the same?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could try to make it like this

const app = new Vue({
  
  el: '#app',
  
  data: {
    scrollPosition: null
  },
  
  methods: {
    updateScroll() {
      this.scrollPosition = window.scrollY
    }
  },
  
  mounted() {
    window.addEventListener('scroll', this.updateScroll);
  }
  
})

You should also consider removing event listener when component is being destroyed, in order to prevent leaks:

destroy() {
  window.removeEventListener('scroll', this.updateScroll)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...