这是我的应用程序中的路线示例:
{
path: "/something",
name: "SomeRoute",
component: SomeComponent,
meta: {showExtra: true},
},
{
path: "/somethingElse",
name: "SomeOtherRoute",
component: SomeOtherComponent,
},
然后我有以下组件,您会注意到它有两个
script
标签,一个带有组合 API,一个没有:
<template>
<div>
This will always be visible. Also here's a number: {{ number }}
</div>
<div v-if="showExtra">
This will be hidden in some routes.
</div>
</template>
<script setup lang="ts">
import type { RouteLocationNormalized } from "vue-router"
import { ref } from "vue"
const number = 5
const showExtra = ref(true)
const onRouteChange = (to: RouteLocationNormalized) => {
showExtra.value = !!to.meta?.showExtra
}
</script>
<script lang="ts">
import { defineComponent } from "vue"
export default defineComponent({
watch: {
$route: {
handler: "onRouteChange",
flush: "pre",
immediate: true,
deep: true,
},
},
})
</script>
这工作正常:当我使用
meta: {showExtra: false}
输入路线时,它会隐藏额外的 div,否则会显示它。
然而,我想要做的是仅使用组合 API 来实现相同的效果,换句话说,完全删除第二个
<script>
标签。我试过这个:
<script setup lang="ts">
import type { RouteLocationNormalized } from "vue-router"
import { ref } from "vue"
import { onBeforeRouteUpdate } from "vue-router"
// ...
// same as before
// ...
onBeforeRouteUpdate(onRouteChange)
</script>
但是当我切换路线时,这不会按预期生效。我知道我可以导入
watch
函数,但我不确定如何获取有关路线的元信息以及如何安抚类型检查器。
您可以通过从 vue 导入
watch
方法将您的观察者转换为组合 API
<script lang="ts">
import { defineComponent, vue, watch } from "vue"
import { useRoute } from "vue-router"
export default defineComponent({
setup() {
const route = useRoute()
watch(route, (to) => {
showExtra.value = !!to.meta?.showExtra
}, {flush: 'pre', immediate: true, deep: true})
},
})
</script>
我没有足够的代表来评论,但上面接受的答案在操作上确实有细微的差别。
选项API:
watch: {
'$route': {
handler(oldValue, newValue) => {}
}
}
合成API:
setup() {
const route = useRoute();
watch(route, (newValue, oldValue) => {});
}
在组合API中,oldValue将只是newValue(同一对象)的克隆,而在选项API中,oldValue实际上将是先前的路由(在许多场景中很有用)。