I'm trying to add class name dynamically. That class is changing display of navbar when scroll offset greater than 50.
This is jQuery code (jQuery to collapse the navbar on scroll):
$(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.
CodePudding user response:
Add the scroll event handler in the created() function and change the isSticky variable there.
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:
<nav :>
...
</nav>
CodePudding user response:
You need to use a reactive variable or a 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.
