Vue-Composition API(useRouter & useRoute)

很 hook 的味道。

useRouter & useRoute

以往在用 Options API 控制路由的時候我們會這樣寫:

1
2
3
4
5
6
7
8
9
10
11
methods: {
gonback() {
this.$router.go(-1)
},
goForward() {
this.$router.go(1)
},
redirect() {
this.$router.push('/')
}
}

不過在 Composition API 中因為 setup 沒辦法存取到 this 的關係,所以得改用 useRouteruseRoute 這兩個 hook 來做,用起來會像這樣:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script>
import { useRouter } from 'vue-router'

export default {
setup() {
// get router instance
const router = useRouter()

function goBack() {
router.go(-1)
}
function goForward() {
router.go(1)
}
function redirect() {
router.push('/')
}

return { goBack, goForward, redirect }
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
<script>
import { useRoute } from 'vue-router'

export default {
setup() {
// get route instance
const route = useRoute()
// get params id
console.log(route.params.id)
}
}
</script>

總之這就是在 setup 中存取路由的方式,不得不說還以為我在寫 React 呢 XD

Vue-Router Guard Vue 版的 Custom Hook-Composables
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×