引入
javascript
import { createRouter, createWebHashHistory } from 'vue-router';
路由规则
javascript
const routes = [
{
path: '/',
name: 'main',
component: () => import('@/views/Main.vue')
}
]
routes是一个包含多个路由对象的数组
每个路由对象至少包含两个属性:
- path 是指定的路径
- component 是该路径下对应的组件。
创建路由实例
ini
const router = createRouter({
// 设置路由模式
history: createWebHashHistory(),
routes,
});
createRouter():创建路由实例,接收一个配置对象
- history:指定路由的模式
- routes:一个数组,包含了多个路由对象。
createWebHashHistory:创建一个基于浏览器URL的hash模式
- 在URL中使用
#分隔实际路径http://example.com/#/about- 服务器端无需任何配置即可正常生效
- 缺点:url不太美观(createWebHistory更美观,但需要服务器端进行配置)
导出路由实例
arduino
export default router;
注册路由
两种情况:
在main.js中注册路由,在组件中可以直接使用
this.$router和this.$route
this.$router:导航到不同页面:
this.$router.push({ name: 'main' })
this.$route:获取当前路由信息:
this.$route.path 或 this.$route.name未在main.js中注册,在需要使用路由实例的文件中手动引入 router
注册:
js
// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router'; // 引入路由实例
const app = createApp(App);
app.use(router); // 使用路由实例
app.mount('#app');
使用:
vue
<script>
...
this.$router.push({ name: 'main' }); // 直接使用 this.$router
...
</script>
未注册:
js
<script>
import router from '../router'; // 手动引入路由实例
export default {
methods: {
navigateToMain() {
router.push({ name: 'main' }); // 使用手动引入的 router
}
}
}
</script>
组件中使用路由
<router-view>组件中的占位符,显示的内容根据当前路由决定
js
<script setup></script>
<template>
<!--占位符-->
<router-view></router-view>
</template>
<style scoped></style>
补充:命名视图
在一个页面中,使用多个占位符来分别显示不同的组件内容,可以使用命名视图(Named Views)。
命名视图允许你在同一个路由中定义多个
<router-view>,每个视图可以显示不同的组件。
组件配置
js
<script setup>
</script>
<template>
<router-view name="header"></router-view>
<router-view name="main"></router-view>
</template>
<style scoped>
</style>
路由配置
js
...
import HeaderComponent from '@/components/HeaderComponent.vue'
import MainComponent from '@/components/MainComponent.vue'
const routes = [
{
path: '/',
name: 'main',
components: {
header: HeaderComponent,
main: MainComponent
}
}
];