通过包装在 ref() 中的 Reactive Vue Router 对象不起作用

Reactive Vue Router object by wrapping in ref() not working

我有一个应用程序,我想在其中打印类似于面包屑的用户位置。我有一个在应用程序级别添加的组件,并希望它使用当前值或 router.currentRoute 对象进行更新。但是它似乎没有按预期更新。

我正在使用 Vue2 Composition api 插件,并努力将其保持在良好的状态,这将使我能够更轻松地迁移到 Vue3。这意味着我想避免使用可用的 context.$route 对象。我的尝试目前直接导入路由器并将 currentRoute 对象包装在 ref() 中,但这似乎不起作用。

这是一个 CodeSandbox 的应用程序,显示了这个问题。我有一个主页和两个附加页面。阅读“您当前位置是:主页”的文本在导航到那里时应该更改为其他页面的名称,但它根本没有改变。

<template>
  <div>
    <p>Your current location is: {{ location.name }}</p>
  </div>
</template>

<script>
import { defineComponent, ref } from "@vue/composition-api";
import router from "@/router";

export default defineComponent({
  name: "Page1",
  setup() {
    const location = ref(router.currentRoute);

    return { location };
  },
});
</script>

如果有办法按照我想要的方式执行此操作,请告诉我。如果不可能,我会硬着头皮使用 context.$route 并在迁移到 Vue3 时处理更大的重构。

你可以在上面使用 reactive() on the router instance, and then toRef() 得到 currentRoute:

import { defineComponent, reactive, toRef } from '@vue/composition-api'
import router from '@/router'

export default defineComponent({
  setup() {
    const location = toRef(reactive(router), 'currentRoute')
    return { location }
  }
})

Vue 2 demo

你可能会在 Vue 3 中迁移它,因为 Vue 3 中来自 Vue Router 4 的 next version of Vue Router already has different semantics for the Composition API. You could simply use useRoute():

import { defineComponent } from 'vue'
import { useRoute } from 'vue-router'

export default defineComponent({
  setup() {
    const location = useRoute()
    return { location }
  }
})

Vue 3 demo