【问题标题】:VueJS: How to dynamically change a CSS class after a scroll positionVueJS:如何在滚动位置后动态更改 CSS 类
【发布时间】:2017-04-27 00:30:59
【问题描述】:

我正在使用 vueJs 和 bootstrap 创建一个 webapp。我想change CSS class一个元素经过一定量的滚动后,有没有一些vue方法可以做到这一点。

我想要以下内容:

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

我发现的一个选项是使用vue-scroll,这似乎很有希望,但not working

还有其他的本地方法可以达到同样的效果吗?

【问题讨论】:

标签: html css twitter-bootstrap vue.js


【解决方案1】:

你可以试试这样

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

您还应该考虑在组件被销毁时移除事件监听器,以防止泄漏:

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

【讨论】:

  • 我相信 destroyed () { ... } 对 Vue 2 有效,但在 Vue 3 中这已被 unmounted () { ... } 取代
猜你喜欢
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-17
  • 2012-09-10
  • 1970-01-01
  • 2013-09-30
  • 1970-01-01
相关资源
最近更新 更多