路由(Routing)是指确定网站或应用程序中特定页面的方式。在Web开发中,路由用于根据URL的不同部分来确定应用程序中应该显示哪个内容。
- 构建前端项目
npm init vue@latest
//或者
npm init vite@latest
- 安装依赖和路由
npm install
npm install vue-router -S
3. router 使用
login.vue
<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
<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
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
<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
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
router-view
补充:
router-view
是Vue Router提供的一个组件,用于在Vue应用中展示匹配到的路由组件。
在Vue应用的模板中,可以使用<router-view></router-view>
标签来放置router-view
。当访问的路径与路由配置中定义的路由匹配时,对应的路由组件将显示在router-view
的位置。
以下是一个简单的示例:
<template>
<div>
<h1>My App</h1>
<router-view></router-view>
</div>
</template>
在上述例子中,<router-view></router-view>
的位置就是用于展示匹配到的路由组件的地方。当用户访问的路径匹配到了某个路由配置,对应的路由组件将会显示在<router-view>
标签的位置。文章来源:https://www.toymoban.com/news/detail-646052.html
通过使用<router-view>
,我们可以根据不同的路径加载不同的路由组件,从而实现页面的动态切换。文章来源地址https://www.toymoban.com/news/detail-646052.html
到了这里,关于【Vue-Router】路由入门的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!