Vue3 路由基础 01
npm i vue-router
创建src/router/index.ts
index.ts
:
// 创建一个路由器,并暴露出去
// 第一步:引入vue-router
import { createRouter, createWebHistory } from 'vue-router'
// 引入可能要呈现的组件
import Home from '@/components/Home.vue'
import About from '@/components/About.vue'
import News from '@/components/News.vue'
// 创建路由器
const router = createRouter({
history: createWebHistory(), // 路由器的工作模式
routes:[
{
path: '/home',
component:Home
},
{
path: '/news',
component:News
},
{
path: '/about',
component:About
}
]
});
// 暴露出去 router
export default router
main.ts
:
import './assets/main.css'
// 引入createApp,用来创建vue实例
import { createApp } from 'vue'
// 引入根组件
import App from './App.vue'
// 引入路由器
import router from './router'
// 创建vue实例
const app = createApp(App)
// 挂载路由器
app.use(router)
// 挂载实例
app.mount('#app')
App.vue
:
<template>
<div id="app">
<h1>Vue路由测试</h1>
<!-- 导航区 -->
<div class="navigate">
<RouterLink to="/home" active-class="acti-class">首页</RouterLink>
<RouterLink to="/news" active-class="acti-class">新闻</RouterLink>
<RouterLink to="/about" active-class="acti-class">关于</RouterLink>
</div>
<!-- 展示区 -->
<div class="show">
此处以后可能要展示各种组件,到底展示哪个组件,需要看路径
<RouterView></RouterView>
</div>
</div>
</template>
<script lang="ts" setup>
// 引入路由视图组件
import { RouterView , RouterLink} from 'vue-router';
</script>
<style scoped>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
#app {
text-align: center;
margin-top: 50px;
}
h1 {
color: #333;
font-size: 36px;
}
.navigate {
margin: 20px 0;
}
.navigate a {
text-decoration: none;
color: #00ffe1;
font-size: 18px;
margin: 0 15px;
}
.navigate a.acti-class {
color: #0056b3;
}
.show {
border: 1px solid #ddd;
padding: 20px;
margin: 20px;
background-color: #f9f9f9;
font-size: 18px;
color: #555;
border-radius: 8px;
}
</style>
注意点
-
路由组件通常存放在
pages
或views
文件夹,一般组件通常存放在components
文件夹。一般组件:
<Component/>
路由组件:
<RouterView/>
-
通过点击导航,视觉效果上“消失” 了的路由组件,默认是被卸载掉的,需要的时候再去挂载。
router-link和RouterLink区别:
<router-link>
是模板中的写法,用在.vue
文件的<template>
部分,Vue 会自动解析它。RouterLink
是在脚本或 JSX 中的直接引用,用于非模板环境(如组合 API、JSX 或渲染函数)。
它们背后都是指向同一个路由组件,功能是相同的,唯一的区别是使用场景和语法风格不同。
路由器工作模式
-
history
模式优点:
URL
更加美观,不带有#
,更接近传统的网站URL
。缺点:后期项目上线,需要服务端配合处理路径问题,否则刷新会有
404
错误。const router = createRouter({ history:createWebHistory(), //history模式 /******/ })
-
hash
模式优点:兼容性更好,因为不需要服务器端处理路径。
缺点:
URL
带有#
不太美观,且在SEO
优化方面相对较差。const router = createRouter({ history:createWebHashHistory(), //hash模式 /******/ })
to的两种写法
<!-- 第一种:to的字符串写法 -->
<router-link active-class="active" to="/home">主页</router-link>
<!-- 第二种:to的对象写法 -->
<router-link active-class="active" :to="{path:'/home'}">Home</router-link>
命名组件
const router = createRouter({
history: createWebHistory(), // 路由器的工作模式
routes:[
{
name:'jia',
path: '/home',
component:Home
},
{
path: '/news',
component:News
},
{
path: '/about',
component:About
}
]
});
<router-link active-class="active" :to="{name:'jia'}">Home</router-link>
<router-link active-class="active" :to="{path:'/home'}">Home</router-link>
1