npm install vue-router
main.ts引入
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
meta添加路由的其他参数
redirect: '/emit', //重定向
alias: ['/jx', '/jx1', '/jx2'],//别名
children: []//子路由
import {createRouter, createWebHistory, RouteRecordRaw} from 'vue-router'
declare module 'vue-router' {
interface RouteMeta {
title: string
}
}
const routes: Array = [
{
path: '/',
name: 'component',
meta: {title: '123'},
component: () => import('../view/App_component.vue'),
children: [
{
path: '/emit',
components: {
default: () => import('../view/App_emit.vue')
}
},
{
path: '/define',
components: {
aaa: () => import('../view/App_define.vue')
}
},
{
path: '/tsx',
components: {
default: () => import('../view/App_tsx')
}
}
]
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
//createWebHashHistory
/**
* 原理window.addEventListener('hashchange',(e)=>{console.log(e)})
* location.hash = '/bus'
*/
//createWebHistory
/**
* 原理window.addEventListener('popstate',(e)=>{console.log(e)})
* history.pushState({}, '', '/bus')
*/
scrollBehavior
const router = createRouter({
history: createWebHistory(),
scrollBehavior: (to, from, save) => { //记录页面的滚动条位置
console.log(save);
if (save) {
return save
} else {
return {
top: 0
}
}
},
routes
})
RouterView显示路由对应的界面
router.push({path: '/index'})
path就是路由对应的url
router.push({name: 'index'})
name就是路由对应的name
router.push({path: '/index',query:{id:'123'}})
query传参,不需要处理路由
router.push({path: '/index',params:{id:'123'}})
params传参,需要修改路由添加对应参数
例如:path: '/index/:id/:name'
let whileList = ['/', '/bus'];
router.beforeEach((to, from, next) => {
window.document.title = to.meta.title;
if (whileList.includes(to.path)) {
next()
} else {
router.push('/')
}
})
router.beforeResolve((to, from)=>{
})
router.afterEach((to, from) => {
})
beforeEnter: (to, from) => {
},
组件内守卫
beforeRouteEnter(to, from) {
// 不能获取组件实例
},
beforeRouteUpdate(to, from) {
// 组件已经挂载好了,导航守卫可以访问组件实例
},
beforeRouteLeave(to, from) {
// 在导航离开渲染该组件的对应路由时调用,可以访问组件实例
},