在 Vue3 和 Vue-router 中获取当前路线的最佳方式?
Best way to get current route in Vue3 and Vue-router?
我正在尝试使用 Vue3 和 Vue-router 获取当前路径(类似于 "https://example.com/some/path"
)。
之前,在使用 Vue2 时,我可以使用以下方法获取当前路线:
// works with vue 2.x with composition-api, but not with vue 3.x
setup(_, ctx) {
const path = computed(() => ctx.root.$route.path)
但在 Vue3 中无法使用 ctx.root
(as stated by Evan You here).
那么用Vue3获取当前路由的首选方式是什么?
您可以使用可组合函数 useRoute
:
import {useRoute} from 'vue-router'
import {computed} from 'vue'
...
setup(){
const route=useRoute();
const path = computed(() =>route.path)
}
我正在尝试使用 Vue3 和 Vue-router 获取当前路径(类似于 "https://example.com/some/path"
)。
之前,在使用 Vue2 时,我可以使用以下方法获取当前路线:
// works with vue 2.x with composition-api, but not with vue 3.x
setup(_, ctx) {
const path = computed(() => ctx.root.$route.path)
但在 Vue3 中无法使用 ctx.root
(as stated by Evan You here).
那么用Vue3获取当前路由的首选方式是什么?
您可以使用可组合函数 useRoute
:
import {useRoute} from 'vue-router'
import {computed} from 'vue'
...
setup(){
const route=useRoute();
const path = computed(() =>route.path)
}