繁体   English   中英

如何将 JQuery 转换为 Vue.js 脚本

[英]How to convert JQuery to Vue.js Script

我正在尝试动态添加 class 名称。 当滚动偏移量大于 50 时,class 正在更改导航栏的显示。

这是 jQuery 代码(jQuery 在滚动时折叠导航栏):

  $(window).scroll(function() {
    if ($(".navbar-default").offset().top > 50) {
      $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
      $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
  });

这是我尝试过的:

<script>
export default {
  data() {
    return {
      isSticky: false,
      stickyClass: "top-nav-collapse",
    };
  },
  methods: {
    handleScroll(e) {
      e.prevent();
      if (window.scrollY > 50) {
        this.isSticky = true;
        console.log("deneme");
      } else {
        this.isSticky = false;
      }
    },
  },
  mounted() {
    this.handleScroll();
  },
};
</script>

如何转换此代码? 谢谢你的帮助。

您需要使用反应变量或Ref

就像是:

<script>
export default {
  data() {
    const isSticky = ref(false);

    const updateSticky = (newStickyValue) => {
        isSticky.value = newStickyValue;
    };

    return {
      isSticky,
      updateSticky,
      stickyClass: "top-nav-collapse",
    };
  },
  methods: {
    handleScroll(e) {
      e.prevent();
      if (window.scrollY > 50) {
        updateSticky(true); // isSticky.value = true might also work
        console.log("deneme");
      } else {
        updateSticky(false)
      }
    },
  },
  mounted() {
    this.handleScroll();
  },
};
</script>

为经过测试的解决方案发布您的代码的现场演示。

created() function 中添加滚动事件处理程序并在那里更改isSticky变量。

export default {
  data: () => ({
    isSticky: false,
  }),
  created() {
    window.addEventListener("scroll", () => {
      this.isSticky = window.scrollY > 50;
    });
  },
}

然后在您的模板中,您可以像这样添加/删除 class:

<nav class="navbar-fixed-top" :class="{'top-nav-collapse': isSticky}">
    ...
</nav>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM