前言:
vue是前端的三大框架之一,跟随此文来学习:vue的滚动行为和路由元信息把!
一、路由的滚动行为
使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。路由的滚动行为,它让你可以自定义路由切换时页面如何滚动。
const router = new VueRouter({
// 只有调用了history.pushState()的时候才会触发这个方法
mode: 'history',
base: process.env.BASE_URL,
routes,
// 使用这个方法实现期望滚动到哪一位置,
scrollBehavior (to, from, savedPosition) {
console.log(to,from,savedPosition);
// 都是直接到顶部
// return {x:0,y:0}
// 按 前进 或 后退 和原生一致
// if (savedPosition) {
// return savedPosition
// } else {
// return { x: 0, y: 0 }
// }
// 滚动到锚点
if (to.hash) {
return {
selector: to.hash,
// 平滑滚动
behavior: 'smooth',
}
}
// 异步滚动 延迟2秒后返回顶部
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ x: 0, y: 0 })
}, 2000)
})
}
})
二、路由元信息
定义的时候可以配置 meta 字段
通过 meta 字段可以验证需要登录的路由
const routes = [
{
path:'boy',
name:'Boy',
component: () => import('@/views/sex/boy.vue'),
// meta 字段,req可以随意命名
meta:{req:true},
},
{
path:'girl',
name:'Girl',
component: () => import('@/views/sex/girl.vue')
}
]
// 模拟登录功能
let login = true
router.beforeEach((to,from,next)=>{
// 加载功能
NProgress.start()
if(to.meta.req){
if(login){
next()
}else{
next({path:'home'})
}
}else{
next()
}
})
三、路由的二种模式
hash 模式:
url 地址栏中存在 `#` 号的网址
history 模式:
url 地址栏中不存在 `#` 号的网址
四、重定向,别名
在路由规则中,可采用redirect来重定向另一个地址
// 路径写法
const routes = [{ path: '/home', redirect: '/' }]
// 命名写法
const routes = [{ path: '/home', redirect: { name: 'home' } }]
别名表示访问url时自由命名,不受约束,router会自动进行别名匹配,就像我们设置/的别名为/home,相当于访问 /
// alias是别名的key
const routes = [{ path: '/', component: HomeView, alias: '/home' }]
以上就是路由滚动行为和路由元信息的使用方法,还有不懂得地方可以在评论区里问我,以后会持续发布一些新文章,敬请关注。
我的其他文章:https://blog.csdn.net/weixin_62897746?type=blog