[英]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.