Vue3【二十一】Vue 路由模式(createWebHashHistory /createWebHistory )和RouterLink写法
实例截图

目录结构

代码
app.vue
<template>
<div class="app">
<Header></Header>
<div class="navigate">
<RouterLink to="/home" active-class="active"> 首页 </RouterLink>
<RouterLink :to="{name:'xinwen'}" active-class="active"> 新闻 </RouterLink>
<RouterLink :to="{path:'/about'}" active-class="active"> 关于 </RouterLink>
</div>
<div class="main-content">
<RouterView />
</div>
</div>
</template>
<script lang="ts" setup name="App">
import { RouterView } from 'vue-router';
import Header from '@/components/Header.vue';
</script>
<style scoped>
.app {
background-color: #4fffbb;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 10px;
}
.navigate {
display: flex;
justify-content: space-around;
margin: 0 100px;
}
.navigate a {
display: block;
text-align: center;
width: 90px;
height: 40px;
line-height: 40px;
border-radius: 10px;
background-color: #818080;
text-decoration: none;
color: #fff;
letter-spacing: 5px;
}
.navigate a.active {
color: #ffc268;
background-color: #fff;
border: 1px solid #ffc268;
font-weight: 900;
font-family: 微软雅黑;
}
.main-content {
margin: 0 auto;
margin-top: 30px;
margin-bottom: 30px;
border-radius: 10px;
width: 90%;
height:400px;
border: 1px solid;
}
</style>
Header.vue
<template>
<h2 class="title">Vue3 路由和组件页面切换测试</h2>
</template>
<script setup lang="ts" name="Header">
</script>
<style scoped>
.title{
text-align: center;
word-spacing: 5px;
margin: 30px 0;
height: 70px;
line-height: 70px;
background-image: linear-gradient(45deg, #cecece, #fff);
border-radius: 10px;
box-shadow: 0 0 2px;
font-size: 30px
}
</style>
index.ts
// 创建一个路由器,并暴漏出去
// 第一步:引入createRouter
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
// 引入各种组件
import Home from '@/pages/Home.vue'
import About from '@/pages/About.vue'
import News from '@/pages/News.vue'
// 第二步:创建路由器
const router = createRouter({
// 配置路由模式
// createWebHistory history模式:url不带#号,需要后端做url适配 适合销售项目 利于seo
// createWebHashHistory Hash模式:url 带#号,不需要url适配,比较适合后端项目 不利于seo
history: createWebHistory(),
// 配置路由规则
routes: [
// { path: '/', redirect: '/home' },
// { path: '/home', component: Home },
// { path: '/about', component: About },
// { path: '/news', component: News }
// 路由命名
{ path: '/', redirect: '/home' },
{ path: '/home', name: 'zhuye', component: Home },
{ path: '/about', name: 'guanyu', component: About },
{ path: '/news', name: 'xinwen', component: News }
]
})
// 第三步:导出路由器
export default router
home.vue
<template>
<div class="home">
<img src="/public/logo.png" alt="">
</div>
</template>
<script setup lang="ts" name="Home">
</script>
<style scoped>
.home {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
img {
width: 10%;
}
</style>