Skip to content

Commit

Permalink
捕獲所有路由或 404 Not found 路由
Browse files Browse the repository at this point in the history
  • Loading branch information
malagege committed Jun 16, 2021
1 parent 9649555 commit ef8040a
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/components/NotFound.vue
@@ -0,0 +1,24 @@
<template>
<div>
Not Found 404
<br>
<button v-on:click="test"> on test</button>
</div>
</template>


<script>
export default {
methods:{
test(){
console.log(this.$route.path.split('/'));
this.$router.push({
name: 'NotFound',
// :pathMatch 為 下面參數可以帶入
// http://localhost:3000/#/123/456
params: { pathMatch: ['123','456'] },
})
}
}
}
</script>
10 changes: 10 additions & 0 deletions src/components/User.vue
@@ -1,6 +1,8 @@
<template>
<div>
User {{ $route.params.id }}
<br>
<button v-on:click="test"> on test</button>
</div>
</template>

Expand All @@ -20,5 +22,13 @@ export default {
// this.userData = await fetchUser(to.params.id)
console.log('to',to,'from',from);
},
methods:{
test(){
this.$router.push({
name: 'NotFound',
params: { pathMatch: this.$route.path.split('/') },
})
}
}
}
</script>
20 changes: 20 additions & 0 deletions src/components/UserGeneric.vue
@@ -0,0 +1,20 @@
<template>
<div>
UserGeneric paramter.afterUser: {{ $route.params.afterUser}}
<br>

</div>
</template>

<script>
export default {
methods:{
test(){
this.$router.push({
name: 'NotFound',
params: { pathMatch: this.$route.path.split('/') },
})
}
}
}
</script>
6 changes: 6 additions & 0 deletions src/main.js
Expand Up @@ -4,6 +4,8 @@ import App from './App.vue'
import Home from './components/Home.vue'
import About from './components/About.vue'
import User from './components/User.vue'
import NotFound from './components/NotFound.vue'
import UserGeneric from './components/UserGeneric.vue'


// 2. 定義一些路由
Expand All @@ -14,6 +16,10 @@ const routes = [
{ path: '/about', component: About },
// 動態段以冒號開始
{ path: '/users/:id', component: User },
// 將匹配所有內容並將其放在 `$route.params.pathMatch` 下
{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
// 將匹配以 `/user-` 開頭的所有內容,並將其放在 `$route.params.afterUser` 下
{ path: '/user-:afterUser(.*)', component: UserGeneric },
]

// 3. 創建路由實例並傳遞 `routes` 配置
Expand Down

0 comments on commit ef8040a

Please sign in to comment.