路由模式createWebHashHistory 和 createWebHistory 的区别
时间: 2023-06-06 19:09:14 浏览: 42
createWebHistory 是基于浏览器的 HTML5 history API 实现的,它可以实现路由的前进后退功能,但需要后端服务器的支持,因为它将路由信息保存在浏览器的 history 栈中,会发生浏览器刷新页面时会丢失路由信息。而 createWebHashHistory 利用 URL 的 hash 值实现路由,不需要服务器支持,同时也不会丢失路由信息。因此,createWebHashHistory 适合于纯前端开发的应用,而 createWebHistory 适合服务端渲染的应用。
相关问题
vue router hash 和 history
Vue Router 提供了两种路由模式:hash 模式和 history 模式。
1. Hash 模式:
在 hash 模式下,URL 中的路由会以 "#/" 开头,例如:http://example.com/#/home。这种模式下,路由的改变不会导致页面的刷新,而是通过监听 URL 的 hash 值变化来实现路由切换。Vue Router 默认使用的就是 hash 模式。
2. History 模式:
在 history 模式下,URL 中的路由不再带有 "#/",例如:http://example.com/home。这种模式下,路由的改变不会有 "#" 符号出现在 URL 中,看起来更加美观。但是需要注意的是,history 模式需要服务器端的支持,因为在 history 模式下刷新页面或直接访问某个 URL 时,会向服务器发送请求,所以需要配置服务器以返回正确的页面。
你可以通过以下方式配置 Vue Router 的路由模式:
```javascript
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
const router = createRouter({
history: createWebHashHistory(), // 使用 hash 模式
// history: createWebHistory(), // 使用 history 模式
routes: [
// 路由配置
],
});
```
其中,`createWebHashHistory()` 创建 hash 模式的路由实例,`createWebHistory()` 则创建 history 模式的路由实例。根据需要选择相应的模式进行配置。
vue3路由配置子路由
在 Vue 3 中,你可以使用 `createRouter` 函数来创建路由实例,并使用 `createWebHistory` 或 `createWebHashHistory` 创建路由模式。在路由实例中,你可以使用 `routes` 属性来配置路由的各个路由项。
要配置子路由,你可以在父级路由项的 `children` 属性中定义子路由项的配置。每个子路由项都是一个对象,包含 `path`(路径)、`component`(组件)等属性。
以下是一个简单的示例:
```javascript
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
{
path: '/',
component: Home,
children: [
{
path: 'about',
component: About
},
{
path: 'contact',
component: Contact
}
]
}
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
```
在上面的示例中,根路由项配置了两个子路由项:`about` 和 `contact`。当访问 `/about` 路径时,会渲染 `About` 组件;当访问 `/contact` 路径时,会渲染 `Contact` 组件。
记得在根组件中添加 `<router-view />` 标签,这样子路由才能正确地渲染到父组件中。
这只是一个简单的示例,你还可以根据自己的需求进行更复杂的子路由配置。希望能对你有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![mp4](https://img-home.csdnimg.cn/images/20210720083504.png)