How to access current route name reactively in Vue Composition API in TypeScript?

Viewed 16650

How can I access current route name, reactively, with Vue Router using Vue Composition API in Vue 3 with TypeScript?

2 Answers

Here are examples using Vue 3.0 and Vue Router v4.0.0-beta.12 with Composition API syntax:

<script lang="ts">
import { defineComponent, computed, watch } from 'vue';
import { useRoute } from 'vue-router';

export default defineComponent({
  name: 'MyCoolComponent',
  setup() {
    const route = useRoute();
    
    console.debug(`current route name on component setup init: ${route.name}`);

    // You could use computed property which re-evaluates on route name updates
    // const routeName = computed(() => route.name);

    // You can watch the property for triggering some other action on change
    watch(() => route.name, () => {
      console.debug(`MyCoolComponent - watch route.name changed to ${route.name}`);
      // Do something here...

    // Optionally you can set immediate: true config for the watcher to run on init
    //}, { immediate: true });
    });
    
    return { route };
  },
});
</script>

<template>
  <p>Current route name: {{ route.name }}</p>
</template>

Or by using the currently experimental Script Setup syntax, SFC Composition API Syntax Sugar, for Composition API:

<script setup lang="ts">
import { computed, watch } from 'vue';
import { useRoute } from 'vue-router';

export const name = 'MyCoolComponent';

export const route = useRoute();
    
console.debug(`current route name on component setup init: ${route.name}`);

// You could use computed property which re-evaluates on route name updates
//export const routeName = computed(() => route.name);

// You can watch the property for triggering some other action on change
watch(() => route.name, () => {
  console.debug(`MyCoolComponent - watch route.name changed to ${route.name}`);
  // Do something here...

  // Optionally you can set immediate: true config for the watcher to run on init
//}, { immediate: true });
});
</script>

<template>
  <p>Current route name: {{ route.name }}</p>
</template>

Here's my example which is for watching route params instead. This question comes up when generally searching for how to watch route params in Vue 3.

<script setup lang="ts">
import axios from 'axios'
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const page = ref<any>({})

const fetchPage = async () => {
    console.log('route', route.params)
    const { data } = await axios.get(
        `/api/${route.params.locale}/pages/${route.params.slug}`,
        {
            params: {
                include: 'sections,documents,courses',
            },
        }
    )

    page.value = data.data
}

onMounted(() => {
    fetchPage()
})

watch(() => route.params.slug, fetchPage)
</script>

In my example, route.name doesn't change but route.params.slug changes.

Related