跳至主要内容

[Vue Router] OptionsAPI操作Router方法

TL;DR

Vue Router可以透過this.$router做到許多操作。

包含回到上一頁,甚至臨時新增路由都可以做到。

前置作業

範例會使用到Bootstrap的元件,所以需要先將Bootstrap給引入使用。

(引入Bootstrap參考)

參考資料

相關連結


$route

可以透過Options API透過this.$route調用出目前路由的參數

在路由表(route)設定:id,則會對應到this.$route.params.id

使用https://domain/#/url?search=test,則可以透過$this.$route.query.search取得test的值

./src/router/index.js
import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const router = createRouter({
history: createWebHashHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/newpage',
name: '新增頁面',
component: () => import('../views/NewPage.vue'),
children: [
...
{
path: 'routerNavigation',
component: ()=> import('@/views/RouterNavigation.vue')
},
{
path: 'routerNavigation/:testparams',
component: ()=> import('@/views/RouterNavigation.vue')
},
...
]
}
]
})
export default router

./src/views/RouterNavigation.vue
<script>
export default {
data() {
return {...}
},
methods: {...},
created(){
console.log(this.$route.params)
console.log(this.$route.query)
}
}
</script>

url:http://localhost:5173/#/newpage/routernavigation/abcdefg?search=testsearch

params跟query

this.$route

this.$route 的內容

$router

$router是一個物件,裡面有許多可以調用的路由方法。包含臨時新增路由,回到上一頁等等。可以參考官方提供的methos

./src/views/RouterNavigation.vue
<template>
<div class="d-flex gap-2 flex-wrap">
<h3 class="w-100">點擊觀看console</h3>
<button type="button" class="btn btn-secondary" @click="getRouter">getRouter</button>
<button type="button" class="btn btn-primary" @click="getRoute">getRoute</button>
<hr class="w-100">
<div class="w-100">
<h3>點擊轉換頁面(有歷史記錄)</h3>
<p>可以帶入字串的路由/物件的name(同RouterLink的to)</p>
<button type="button" class="btn btn-success me-2" @click="routerPush1">routerPushByString</button>
<button type="button" class="btn btn-danger" @click="routerPush2">routerPushByName</button>
</div>
<hr class="w-100">
<div class="w-100">
<h3>點擊轉換頁面(沒有歷史記錄)</h3>
<button type="button" class="btn btn-warning" @click="routerReplace">routerReplace</button>
</div>
<hr class="w-100">
<div class="w-100">
<h3>-1代表回到上一頁</h3>
<button type="button" class="btn btn-info" @click="routerGo">routerGo</button>
</div>
<hr class="w-100">
<div class="w-100">
<h3>臨時新增路由</h3>
<button type="button" class="btn btn-primary" @click="routerAddRoute">routerAddRoute</button>
</div>
</div>
</template>

<script>
export default {
data() {
return {
}
},
methods: {
getRoute() {
console.log(this.$route);
},
getRouter() {
console.log(this.$router);
},
routerPush1() {
this.$router.push('/newpage/dynamicRouterByProps/81a0b89d11fb45c2');
},
routerPush2() {
this.$router.push({
name: '新增頁面內的元件A'
});
},
routerReplace() {
this.$router.replace({
name: '新增頁面內的元件A'
});
},
routerGo() {
this.$router.go(-1);
},
routerAddRoute() {
this.$router.addRoute({
path: '/newabout',
name: 'newabout',
component: () => import('@/views/AboutView.vue')
})
}
},
created(){
console.log(this.$route.params)
console.log(this.$route.query)
}
}
</script>