如何访问 当前路线名称 , react 性地,与 Vue路由器使用 Vue 组合 API 在 带有 TypeScript 的 Vue 3 ?
最佳答案
以下是使用 的示例Vue 3.0 和 Vue 路由器 v4.0.0-beta.12 与 组合 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>
关于javascript - 如何在 TypeScript 的 Vue Composition API 中响应式访问当前路由名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63800831/