首页 > 解决方案 > 如何在 TypeScript 的 Vue Composition API 中响应式访问当前路由名称?

问题描述

如何使用Vue Router在Vue 3 中使用Vue Composition API和 TypeScript以响应方式访问当前路由名称

标签: javascripttypescriptvue.jsvue-routervuejs3

解决方案


以下是使用带有Composition API语法的Vue 3.0Vue Router v4.0.0-beta.12 的示例:

<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 组合 API 语法糖,用于组合 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>

推荐阅读