MUKI AI Summary
使用 Vue3 可以監聽路由變化,解決瀏覽器「上一頁」「下一頁」按鈕切換時,選單 active
樣式不變的問題。
透過 watch
監聽 currentRoute
,每次路由變化時更新 activeIndex
,確保選單樣式隨路由變化而更新。...
如果選單有使用類似 active
的 class 設定樣式,那麼用瀏覽器的「上一頁」,「下一頁」功能時,該怎麼隨之切換選單的 active
樣式呢?
▼ Vue3 可以直接監聽路由的變化,實作如下:
<script lang="ts" setup> import { ref, watch } from 'vue' import { useRouter } from 'vue-router' const { currentRoute } = useRouter() const activeIndex = ref<string>(`/${currentRoute.value.path.split('/')[1]}`) watch(currentRoute, (to) => { activeIndex.value = `/${to.path.split('/')[1]}` }) </script>
歡迎給我點鼓勵,讓我知道你來過 :)