如何在 TypeScript 的 Vue Composition API 中反应性地访问当前路由名称?

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

如何使用 Vue 组合 Vue 组合 Vue Router 反应性地访问 当前路由名称,APIVue 3 中使用 TypeScript?

以下是使用 Vue 3.0Vue Router v4.0.0-beta.12Composition API 语法:

<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>

或者使用当前实验性的脚本设置语法SFC Composition API Syntax Sugar,用于组合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>

这是我的例子,它是用来代替观察路由参数的。通常搜索如何在 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>

在我的例子中,route.name 没有改变,但 route.params.slug 改变了。