【Vue-Router】路由入门

路由(Routing)是指确定网站或应用程序中特定页面的方式。在Web开发中,路由用于根据URL的不同部分来确定应用程序中应该显示哪个内容。

  1. 构建前端项目
js 复制代码
npm init vue@latest
//或者
npm init vite@latest
  1. 安装依赖和路由
js 复制代码
npm install
npm install vue-router -S
  1. router 使用

login.vue

html 复制代码
<template>
  <div>
    <div class="login">login</div>
  </div>
</template>

<script setup lang="ts">

</script>

<style scoped>
.login {
  background-color: red;
  height: 400px;
  width: 400px;
  font-size: 20px;
  color: white;
}
</style>

reg.vue

html 复制代码
<template>
  <div>
    <div class="reg">reg</div>
  </div>
</template>

<script setup lang="ts">

</script>

<style scoped>
.reg {
  background-color: green;
  height: 400px;
  width: 400px;
  font-size: 20px;
  color: white;
}
</style>

index.ts

ts 复制代码
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: () => import("../components/login.vue")
  },
  {
    path: "/reg",
    component: () => import("../components/reg.vue")
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

App.vue

html 复制代码
<template>
  <h1>hello world</h1>
  <div>
    <router-link to="/">Login</router-link>
    <router-link style="margin: 10px;" to="/reg">Reg</router-link>
  </div>
  <hr>
  <router-view></router-view>
</template>

<script setup lang="ts">

</script>

<style scoped>

</style>

main.ts

ts 复制代码
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
相关推荐
二狗哈3 分钟前
Cesium快速入门17:与entity和primitive交互
开发语言·前端·javascript·3d·webgl·cesium·地图可视化
GISer_Jing33 分钟前
AI驱动营销增长:7大核心场景与前端实现
前端·javascript·人工智能
星光不问赶路人42 分钟前
new Array() 与 Array.from() 的差异与陷阱
javascript·面试
T___T44 分钟前
Vue 3 做 todos , ref 能看懂,computed 终于也懂了
前端·javascript·面试
bug总结1 小时前
vue+A*算法+canvas解决自动寻路方案
前端·vue.js·算法
cindershade1 小时前
JavaScript 事件循环机制详解及项目中的应用
前端·javascript
王霸天1 小时前
🚀 告别“变形”与“留白”:前端可视化大屏适配的终极方案(附源码)
前端·javascript
LYFlied1 小时前
Vue版本演进:Vue3、Vue2.7与Vue2全面对比
前端·javascript·vue.js
VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue非遗传承文化管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
在掘金801101 小时前
RequireJS 详解
前端·javascript