【发布时间】:2023-12-16 07:16:01
【问题描述】:
如何通过 Vue 路由器 在 Vue 3 with TypeScript?
【问题讨论】:
标签: javascript typescript vue.js vue-router vuejs3
如何通过 Vue 路由器 在 Vue 3 with TypeScript?
【问题讨论】:
标签: javascript typescript vue.js vue-router vuejs3
以下是使用 Vue 3.0 和 Vue Router v4.0.0-beta.12 和 Composition 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,用于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>
【讨论】:
这是我的示例,用于查看路线参数。一般搜索如何在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 会改变。
【讨论】:
slug 是我应用程序中的路由参数。它来自路径/something/:slug等vue-router文件。仔细检查我放置console.log('route', route.params) 的代码。你可以在那里看到你的。注意useRoute 的导入。