【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')
相关推荐
老华带你飞2 分钟前
工会管理|基于springboot 工会管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·spring
GISer_Jing11 分钟前
AI赋能前端:从核心概念到工程实践的全景学习指南
前端·javascript·aigc
不爱吃糖的程序媛20 分钟前
Flutter-OH OAuth 鸿蒙平台适配详细技术文档
javascript·flutter·harmonyos
前端OnTheRun27 分钟前
如何禁用项目中的ESLint配置?
javascript·vue.js·eslint
前端无涯33 分钟前
APP 内嵌 H5 复制功能实现:从现代 API 到兼容兜底方案
javascript
打工人小夏1 小时前
vue3使用transition组件,实现过度动画
前端·vue.js·前端框架·css3
LFly_ice1 小时前
Next-1-启动!
开发语言·前端·javascript
仰望.1 小时前
vue 甘特图 vxe-gantt table 依赖线的使用,配置连接线
vue.js·甘特图
cc蒲公英1 小时前
vue nextTick和setTimeout区别
前端·javascript·vue.js
sinat_384241091 小时前
OpenSpeedy 是一款开源免费的游戏变速工具
javascript