由 Vue Router 所定義的 Route,可透過 <RouterLink>
或 push()
切換。
Version
Vue 3.4
Vue Router 4.2
RouterLink
HomeView.vue
<template>
<div>This is Home View</div>
<RouterLink :to="{ name: 'about' }">About</RouterLink>
</template>
<RouterLink>
為 Vue Router 內建的 component,傳入to
prop 切換網址,以name
指定 route name<RouterLink>
相當於 HTML 的<a>
About.vue
<template>
<div>This is About View</div>
<div>Route name: {{ route.name }}</div>
</template>
<script setup>
import { useRoute } from 'vue-router'
let route = useRoute()
</script>
useRoute()
:取得目前route
objectroute.name
:顯示目前 route 的name
push()
HomeView.vue
<template>
<div>This is Home View</div>
<button @click="onClick">About</button>
</template>
<script setup>
import { useRouter } from 'vue-router'
let { push } = useRouter()
let onClick = () => push({ name: 'about' })
</script>
useRouter()
:取得 Vue Router Object,從該 object 取出push()
push()
:跳轉到其他 route,一樣傳入 object,以name
指定 route name
AboutView.vue
<template>
<div>This is About View</div>
<div>Route name: {{ route.name }}</div>
</template>
<script setup>
import { useRoute } from 'vue-router'
let route = useRoute()
</script>
AboutView
部分不變
Conclusion
- 實務上若多個 route 共用一個 view,可用 route object 的
name
加以判斷