下面是关于Vue3中路由hash与History的设置的详细攻略:
下面是关于Vue3中路由hash与History的设置的详细攻略:
1. 路由设置
在Vue3中使用路由需要先安装vue-router
,使用以下命令进行安装:
npm install vue-router@4
1.1 history模式
如果使用history模式,则路由使用的是浏览器的history.pushState
和history.replaceState
方法,这样路由就是“干净”的URL,可以去除URL中的#
符号,例如:
const router = createRouter({
history: createWebHistory(),
routes,
})
1.2 hash模式
如果使用hash模式,则路由使用的是浏览器的URL中的#
符号,例如:
const router = createRouter({
history: createWebHashHistory(),
routes,
})
使用createWebHashHistory()
方法来创建hash模式的路由。
2. 设置默认路由
设置默认路由可以让用户在没有输入路由路径时自动跳转到指定页面。
2.1 history模式下设置默认路由
在history模式下设置默认路由需要在路由最后添加一个{path: '*', redirect: '/'}
的路由,例如:
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: About,
},
// 设置默认路由
{
path: '*',
redirect: '/',
},
]
2.2 hash模式下设置默认路由
在hash模式下设置默认路由需要在路由最后添加一个`{path: '/'},例如:
const routes = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: About,
},
// 设置默认路由
{
path: '/',
},
]
这里需要注意的是,hash模式下的默认路由不能使用redirect
属性,因为hash路由不存在重定向问题。
示例说明
下面给出两个具体的示例:
示例1:使用history模式设置默认路由
// 引入Vue Router
import { createRouter, createWebHistory } from 'vue-router'
// 引入组件
import Home from '@/views/Home.vue'
import About from '@/views/About.vue'
// 创建路由实例
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: About,
},
// 设置默认路由
{
path: '*',
redirect: '/',
},
],
})
// 导出路由
export default router
这个示例演示了如何使用history模式设置默认路由。
示例2:使用hash模式设置默认路由
// 引入Vue Router
import { createRouter, createWebHashHistory } from 'vue-router'
// 引入组件
import Home from '@/views/Home.vue'
import About from '@/views/About.vue'
// 创建路由实例
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: About,
},
// 设置默认路由
{
path: '/',
},
],
})
// 导出路由
export default router
这个示例演示了如何使用hash模式设置默认路由。
本文标题为:vue3中关于路由hash与History的设置


基础教程推荐
- 用javascript实现画图效果的代码 2023-12-02
- FF IE浏览器修改标签透明度的方法 2023-12-01
- 「HTML+CSS」--自定义加载动画【028】 2023-10-27
- JavaWeb表单注册界面的实现方法 2023-12-12
- 关于ajax异步访问数据的问题 2023-02-23
- JS对select控件option选项的增删改查示例代码 2023-12-20
- JS利用cookies设置每隔24小时弹出框 2024-01-29
- 在苹果Mac中如何将html网页转成PDF文件? 2023-10-26
- PHP-Zend_Form:HTML表格中带有复选框的数据库记录 2023-10-26
- Vue2.0 $set()的正确使用方式 2023-10-08