javascript - 如何在 TypeScript 的 Vue Composition API 中响应式访问当前路由名称?
问题描述
如何使用Vue Router在Vue 3 中使用Vue Composition API和 TypeScript以响应方式访问当前路由名称?
解决方案
以下是使用带有Composition API语法的Vue 3.0和Vue 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>
推荐阅读
- git - git - 显示更改文件的文件名和文件大小?
- python-2.7 - Tkinter 删除放置在画布上的框架在一个画布上工作,但在另一个画布上无效
- react-native - 仅从 DateTimePickerModal 中提取月份和年份反应原生
- scala - Spark 以编程方式连接到远程 kerberos 保护的 HIVE
- reactjs - 评级反应逻辑
- python - 如何设置keras LSTM的输入形状
- git - gitignore 中路径/文件结尾注释的区别
- mysql - 如何计算出现在列中特定字母之后的字母?
- ios - 在 iOS 如何处理 EXC_RESOURCE RESOURCE_TYPE_MEMORY 错误?
- html - 如何遮盖需要可点击的 div?