vue2中如何给一个组件声明它自己的路由地址
时间: 2024-03-20 15:38:41 浏览: 23
在Vue2中,可以使用Vue Router来声明组件的路由地址。以下是简单的示例代码:
1. 在Vue Router中声明路由和组件的映射关系
```javascript
import Vue from 'vue'
import VueRouter from 'vue-router'
import MyComponent from './components/MyComponent.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/my-component',
component: MyComponent
}
]
const router = new VueRouter({
routes
})
export default router
```
2. 在组件中使用路由地址
```html
<template>
<div>
This is my component.
</div>
</template>
<script>
export default {
name: 'MyComponent',
mounted() {
console.log('My component is mounted.')
}
}
</script>
```
在这里,我们将MyComponent组件映射到路由地址"/my-component"。在组件中,我们不需要手动声明它的路由地址,因为Vue Router会自动将路由地址注入到组件中的$route属性中。我们可以通过$route.path来获取当前组件的路由地址。
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)