VueJS: How to dynamically change a CSS class after

2019-04-28 03:36发布

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?

1条回答
\"骚年 ilove
2楼-- · 2019-04-28 04:16

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 could also remove eventListener on destroy, something like this:

destroy() {
  window.removeEventListener('scroll', this.updateScroll)
}
查看更多
登录 后发表回答