如何对 Vue 3 上的路由更改做出反应,"script setup" 组合 API?

How to react to route changes on Vue 3, "script setup" composition API?

这是我的应用程序中的路由示例:

{
  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 } from "vue"
import { useRoute } from "vuex"

export default defineComponent({
  setup() {
    const route = useRoute()
    watch(route, (to) => {
      showExtra.value = !!to.meta?.showExtra
    }, {flush: 'pre', immediate: true, deep: true})
  },
})
</script>