场景模拟:基础路由配置

引入

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
    }
  }
];
相关推荐
G_G#8 分钟前
纯前端js插件实现同一浏览器控制只允许打开一个标签,处理session变更问题
前端·javascript·浏览器标签页通信·只允许一个标签页
@大迁世界23 分钟前
TypeScript 的本质并非类型,而是信任
开发语言·前端·javascript·typescript·ecmascript
GIS之路32 分钟前
GDAL 实现矢量裁剪
前端·python·信息可视化
是一个Bug35 分钟前
后端开发者视角的前端开发面试题清单(50道)
前端
Amumu1213837 分钟前
React面向组件编程
开发语言·前端·javascript
持续升级打怪中1 小时前
Vue3 中虚拟滚动与分页加载的实现原理与实践
前端·性能优化
GIS之路1 小时前
GDAL 实现矢量合并
前端
hxjhnct1 小时前
React useContext的缺陷
前端·react.js·前端框架
前端 贾公子1 小时前
从入门到实践:前端 Monorepo 工程化实战(4)
前端
菩提小狗2 小时前
Sqlmap双击运行脚本,双击直接打开。
前端·笔记·安全·web安全