场景模拟:基础路由配置

引入

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.$routerthis.$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
    }
  }
];
相关推荐
BY组态5 分钟前
Ricon组态系统最佳实践:从零开始构建物联网监控平台
前端·物联网·iot·web组态·组态
BY组态10 分钟前
Ricon组态系统vs传统组态软件:为什么选择新一代Web组态平台
前端·物联网·iot·web组态·组态
SoaringHeart12 分钟前
Flutter进阶:OverlayEntry 插入图层管理器 NOverlayZIndexManager
前端·flutter
放下华子我只抽RuiKe522 分钟前
React 从入门到生产(四):自定义 Hook
前端·javascript·人工智能·深度学习·react.js·自然语言处理·前端框架
IT_陈寒2 小时前
Redis缓存击穿把我整不会了,原来还有这手操作
前端·人工智能·后端
idcu2 小时前
深入 Lyt.js 组件系统:L2 渲染引擎层的核心
前端·typescript
这是程序猿3 小时前
Spring Boot自动配置详解
java·大数据·前端
文心快码BaiduComate3 小时前
干货|Comate Harness Engineering工程实践指南
前端·后端·程序员
还有多久拿退休金3 小时前
一张栈的图,治好你面试答不出 script 阻塞的病
前端·javascript
光辉GuangHui3 小时前
Agent Skill 也需要测试:如何搭建 Skill 评估框架
前端·后端·llm