场景模拟:基础路由配置

引入

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
    }
  }
];
相关推荐
candyTong1 天前
一觉醒来,大模型就帮我排查完页面性能问题
前端·javascript·架构
魔术师Grace1 天前
我给 AI 做了场入职培训
前端·程序员
玩嵌入式的菜鸡1 天前
网页访问单片机设备---基于mqtt
前端·javascript·css
前端一小卒1 天前
我用 Claude Code 的 Superpowers 技能链写了个服务,部署前差点把服务器搞炸
前端·javascript·后端
滑雪的企鹅.1 天前
HTML头部元信息避坑指南大纲
前端·html
一拳不是超人1 天前
老婆天天吵吵要买塔罗牌,我直接用 AI 2 小时写了个在线塔罗牌
前端·ai编程
excel1 天前
如何解决 Nuxt DevTools 中关于 unstorage 包的报错
前端
Rust研习社1 天前
使用 Axum 构建高性能异步 Web 服务
开发语言·前端·网络·后端·http·rust
C澒1 天前
AI 生码 - API2Code:接口智能匹配与 API 自动化生码全链路设计
前端·低代码·ai编程
浔川python社1 天前
HTML头部元信息避坑指南技术文章大纲
前端·html