const $route = useRoute() 和const $router = useRouter()的区别
时间: 2024-05-17 21:14:42 浏览: 15
在Vue.js中,$route和$router都是Vue Router提供的对象,用于处理路由相关的功能,但它们的作用不同。
- $route是当前路由对象,包含了当前路由的信息,例如当前路由的路径、参数、查询、hash等等。可以通过$route来获取当前路由的信息,比如$route.path、$route.query等等。
- $router是路由器对象,用于实现路由的跳转、导航等功能。通过$router.push、$router.replace等方法可以实现路由的跳转,通过$router.go、$router.back等方法可以实现路由的导航。
所以,$route和$router虽然都是Vue Router提供的对象,但是它们的作用不同,$route用于获取当前路由的信息,$router用于实现路由的跳转、导航等功能。
相关问题
const router = useRouter() const route = useRoute()
这两行代码是在 Vue.js 中使用的,用于获取当前路由的相关信息。
`useRouter()` 是 Vue Router 提供的一个方法,用于返回当前的路由实例,在 Vue 组件中使用时,可以通过 `this.$router` 来访问。
`useRoute()` 也是 Vue Router 提供的一个方法,用于返回当前的路由信息对象,在 Vue 组件中使用时,可以通过 `this.$route` 来访问。
举个例子,如果你想获取当前路由的路径,可以这样写:
```
const router = useRouter()
const route = useRoute()
console.log(router.currentRoute.value.path) // 输出当前路由路径
console.log(route.path) // 输出当前路由路径
```
需要注意的是,这两个方法只能在 Vue 组件中使用,如果在普通的 JavaScript 文件中使用,会抛出错误。
<script setup lang="ts"> import { watch, ref, onMounted } from "vue"; import { useRoute } from "vue-router"; const breadcrumbList = ref<any>([]); const $route = useRoute(); onMounted(() => {}); watch( $route, () => { initBreadcrumbList(); }, { deep: true, immediate: true } ); const initBreadcrumbList = () => { breadcrumbList.value = $route.matched; console.log(breadcrumbList.value); }; </script>这段代码为什么报错
这段代码缺少模板部分,只有 `<script>` 标签是不够的。你需要在 `<template>` 中添加需要渲染的内容,例如:
```html
<template>
<div>
<ul>
<li v-for="breadcrumb in breadcrumbList" :key="breadcrumb.path">
{{ breadcrumb.path }}
</li>
</ul>
</div>
</template>
<script setup lang="ts">
import { watch, ref, onMounted } from "vue";
import { useRoute } from "vue-router";
const breadcrumbList = ref<any>([]);
const $route = useRoute();
onMounted(() => {});
watch(
$route,
() => {
initBreadcrumbList();
},
{ deep: true, immediate: true }
);
const initBreadcrumbList = () => {
breadcrumbList.value = $route.matched;
console.log(breadcrumbList.value);
};
</script>
```
这样就可以正常运行了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)