this.$refs, this.$router, this.$route 访问 Vue 2 Composition API

this.$refs, this.$router, this.$route access with Vue 2 Composition API

你能告诉我如何在 Vue 2 Composition API 设置函数中访问 this.$refsthis.$routerthis.$route 吗? context.$root 提到了一些解决方案,但 $root 不再适用于 context。请帮忙。

我正在使用带有 Composition API 插件的 Vue 2。似乎 useRouteuseRouters 不支持 Vue 2 路由器版本。 useRouteuseRouters 可用于 Vue-router v4。

您可以从其模块导入路由器并从中访问 routerroute

引用可以像在 Vue 3 中一样使用:

import { ref, onMounted } from "@vue/composition-api";   // import ref, onMounted
import router from "@/router";                           // import router

export default {
  setup() {
    console.log(router);                                 // this.$router
    console.log(router.app.$route);                      // this.$route

    const myref = ref(null);                             // create ref
    onMounted(() => {
      console.log(myref);                                // this.$refs.myref
    });

    return { myref };                                    // return for template ref
  },
};