简体   繁体   English

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

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

I'm trying to add class name dynamically.我正在尝试动态添加 class 名称。 That class is changing display of navbar when scroll offset greater than 50.当滚动偏移量大于 50 时,class 正在更改导航栏的显示。

This is jQuery code (jQuery to collapse the navbar on scroll):这是 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");
    }
  });

This is what I tried:这是我尝试过的:

<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>

How can I convert this code?如何转换此代码? Thanks for your help.谢谢你的帮助。

You need to use a reactive variable or a Ref您需要使用反应变量或Ref

Something like:就像是:

<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>

Post a live demo of your code for a tested solution.为经过测试的解决方案发布您的代码的现场演示。

Add the scroll event handler in the created() function and change the isSticky variable there.created() function 中添加滚动事件处理程序并在那里更改isSticky变量。

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

Then in your template you can add/remove the class like this:然后在您的模板中,您可以像这样添加/删除 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