我正在使用 Vue2,并且在動態類系結方面遇到了一些問題(在導航選單欄中突出顯示用戶當前所在的當前部分名稱)。我正在使用我初始化的 Intersection ObserverAPI,并讓它從 mount() 生命鉤子中回圈遍歷我的組件。但是,當我在觀察者中更新當前部分時:
if (active.length) {
this.activeEntry = active[0].target.childNodes[0].id
console.log(this.activeEntry)
}
(完整代碼見下文)它將當前部分“targetEntry”的更改列印到控制臺,但是......我的實際資料“targetEntry”實際上并沒有得到更新/影響(我無法從內部更改資料觀察者?)。我想我在這里混合了一些東西。我如何需要重寫我的觀察者功能(即利用計算)來實際更改我的“targetEntry”資料,以便執行動態類系結?我仍然是 Vue 和 Javascript 的初學者...
提前謝謝了!
<template>
<div id="Navigation-c">
<ul>
<li :class="{ active: activeEntry == 'Entry-c' }" v-scroll-to="'#Entry-c'"><font-awesome-icon icon="fa-solid fa-chevron-up" /></li>
<li :class="{ active: activeEntry == 'Motivation-c' }" v-scroll-to="'#Motivation-c'"><p>Intro</p></li>
<li :class="{ active: activeEntry == 'NeuralNetworks-c' }" v-scroll-to="'#NeuralNetworks-c'"><p>AI</p></li>
<li :class="{ active: activeEntry == 'About-c' }" v-scroll-to="'#About-c'"><p>About</p></li>
<li :class="{ active: activeEntry == 'Contact-c' }" v-scroll-to="'#Contact-c'"><p>Contact</p></li>
</ul>
</div>
</template>
<script>
export default {
name: "Navigation-c",
data: () => ({
activeEntry: '',
observer: null
}),
methods: {
},
updated() {
},
mounted() {
this.observer = new IntersectionObserver(
function (entries) {
const active = entries.filter((e) => e.isIntersecting);
if (active.length) {
this.activeEntry = active[0].target.childNodes[0].id
console.log(this.activeEntry)
}
},
{ threshold: [0.5] }
)
// loop over components
const matches = document.querySelectorAll("section.box");
for (let i = 0; i < matches.length; i ) {
this.observer.observe(matches[i]);
}
},
computed: {
},
created() {
},
};
</script>
<style lang="scss" scoped>
.active {
color: red !important;
}
</style>
uj5u.com熱心網友回復:
關鍵字在不使用箭頭函式this
的情況下丟失了它的背景關系。new IntersectionObserver()
因此,除非您使用箭頭函式重寫,否則嘗試分配this.activeEntry
將不起作用:
mounted() {
this.observer = new IntersectionObserver(
(entries) => { // arrow function!
const active = entries.filter((e) => e.isIntersecting);
if (active.length) {
this.activeEntry = active[0].target.childNodes[0].id
console.log(this.activeEntry)
}
},
{ threshold: [0.5] }
)
// loop over components
const matches = document.querySelectorAll("section.box");
for (let i = 0; i < matches.length; i ) {
this.observer.observe(matches[i]);
}
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/506395.html
標籤:javascript css Vuejs2 交叉观察者 动态类
下一篇:如何僅在一個路由器鏈接中使用組件