Purni
Purni

Reputation: 367

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

Can you please tell me how to access this.$refs, this.$router, this.$route in Vue 2 Composition API setup function? There are solutions mentioned with context.$root but $root is not available with context anymore. Please help.

I am using Vue 2 with Composition API plugin. It seems useRoute or useRouters doesn't support Vue 2 router version. useRoute and useRouters are available with Vue-router v4.

Upvotes: 3

Views: 2200

Answers (1)

Dan
Dan

Reputation: 63089

You could import the router from its module and access both router and route from it.

Refs can be used the same way as in 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
  },
};

Upvotes: 5

Related Questions