/
CATEGORY
Vue
/
Vue3 使用 watch 監聽路由變化,支援瀏覽器的上一頁 / 下一頁按鈕切換

Vue3 使用 watch 監聽路由變化,支援瀏覽器的上一頁 / 下一頁按鈕切換

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>

歡迎給我點鼓勵,讓我知道你來過 :)

9
MUKI says:

如果文章有幫助到你,歡迎分享給更多人知道。文章內容皆為 MUKI 本人的原創文章,我會經常更新文章以及修正錯誤內容,因此轉載時建議保留原出處,避免出現版本不一致或已過時的資訊。

本文地址:https://muki.tw/vue3-router-history-navigate/ 已複製

Subscribe
Notify of
guest

0 則留言
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Copyright © since 2008 MUKI space* / omegaSS theme All Rights Reserved.