vue路由

61 阅读2分钟

路由

1.导航区、展示区

2.请来路由器

3.制定路由的具体规则(什么路径,对应着什么组件)

4.形成一个一个的???.vue)class.vue Subject.vue

1.1配置路由

//第一步:引入createRouter
import {createRouter,createWebHistory} from 'vue-router'
//引入一个一个可能要呈现组件
import Home from '@/components/Home.vue'
import News from '@/components/News.vue'
import About from '@/components/About.vue'
// 第二步:创建路由器
const router =createRouter({
    history:createWebHistory(),//路由器的工作模式
    routes:[
       {
        path:'/home',
        component:Home
       }
   ]
})
export default router                      

1.2main.js配置

//引入createApp用于创建应用
import {createApp} from 'vue'
//引入App根组件
import App from './App.vue
// 引入路由器import router from './route'
createApp(App).mount('#app')
<template>
  <div class="app">
    <h2>Vue路由测试</h2>
    <!-- 导航区 -->
    <div class="navigate">
      <RouterLink to="/login">Login</RouterLink>
    </div>
    <!-- 展示区 -->
    <div class="main-content">
      <RouterView></RouterView>
    </div>  
  </div>
</template><script lang="ts" setup name="App">
import { RouterView, RouterLink } from 'vue-router';
</script><style>
.app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
​
.navigate {
  margin-bottom: 20px;
}
​
.navigate a {
  margin: 0 10px;
  text-decoration: none;
  color: #007bff;
}
​
.navigate a:hover {
  text-decoration: underline;
}
​
.main-content {
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>

2.1vue工程化

1.路由组件通常存放在 pages 或 views 文件夹,一般组件通常存放在 component。

2通过点击导航。,视觉效果上“消失”了的路由组件,默认是被卸载掉的,需要的时候再去挂载。

//借助生命周期onMounted/onUnmounted区分视图状态。

路由组件:靠路由的规则渲染出来的。

一般组件:亲手写标签出来的。

3.1前端框架路由模式

3.1.1history

优点: URL 更加美观,不带有 #,更接近传统的网站 URL。 缺点:后期项目上线,需要服务端配合处理路径问题,否则刷新会有 404 错误。

3.1.2hash模式

优点:兼容性更好,因为不需要服务器端处理路径。

缺点: URL 带有 #不太美观,且在 SE0 优化方面相对较差

4.to的写法

4.1.<RouterLinkto="/home"active-class="active">首页</RouterLink>
4.2<RouterLink:to="{name:'xinwen'}"active-class="active">新闻</RouterLink>
4.3<RouterLink:to="{path:'/about'}"active-class="active">关于</RouterLink>