麦子哥教Vue3.0-路由监听
代码开发
- router路由设置
在 src下建立一个文件夹router 在router下建立index.js
import { createRouter, createWebHistory } from 'vue-router'
import HelloWorld from '../components/HelloWorld.vue'
const routerHistory = createWebHistory()
const router = createRouter({
history: routerHistory,
routes: [
{
path: '/',
name: 'Home',
component: () => import('../components/Home.vue')
},
{
path: '/h',
component: HelloWorld
},
]
})
export default router;
路由基础
由于我们在main.js中注册了app.use(router)
所以我们访问当前路由
//当前路径实体
this.$route
//查询当前路径
this.$route.path
//替换当前路径,历史不会记录
this.$route.replace('/user/login')
//路由跳转,历史会记录,可以返回上一级
this.$route.push('/user/login')
//路由跳转带参数,结果是 /register?plan=private
this.$route.push({ path: '/register', query: { plan: 'private' } })
//路由到锚点,结果是 /about#team
this.$route.push({ path: '/about', hash: '#team' })
//终极杀器
window.history.go(n)
路由嵌套
这里的 是一个顶层的 router-view。它渲染顶层路由匹配的组件。同样地,一个被渲染的组件也可以包含自己嵌套的 `。`
比如我们想让其他组件显示在user组件中怎么实现呢?
const User = {
template: `
User {{ $route.params.id }}
`,
}
要将组件渲染到这个嵌套的 router-view 中,我们需要在路由中配置 children:
const routes = [
{
path: '/user/:id',
component: User,
children: [
{
// 当 /user/:id/profile 匹配成功
// UserProfile 将被渲染到 User 的 内部
path: 'profile',
component: UserProfile,
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 将被渲染到 User 的 内部
path: 'posts',
component: UserPosts,
},
],
},
]
路由监听
注意:路由监听一般放在created方法里面
$watch监听路由变化
//$watch监听路由变化
this.$watch(()=>this.$route.path,(to,from)=>{
console.log("路由发生变化:",to,from);
});
//输出结果:路由发生变化: /pc/lib/user/add /pc/lib/user/update
watch函数监听路由参数变化
watch:{
$route(to,from){
console.log("路由发生变化:",to,from);
}
},
路由缓存问题
当vue多个路径共用一个组件的时候,组件不会重新创建,也就是组件的生命周期不会被重新调用,当页面a切换到c时,在切换的过程中,vue会判断下一个路由的组件是否和当前的路由组件一样,如果一样,就直接复用,因此不会执行destroy等生命周期函数。
问题:当新增和修改共用一个组件的时候,组件的数据会重复使用,导致数据混乱,而且声明周期函数无法调用执行
组件导航守卫监听
组件导航守卫监听
beforeRouteEnter (to, from) {
// 在渲染该组件的对应路由被验证前调用
// 不!能!获取组件实例 `this`
// 因为当钩子执行前,组件实例还没被创建
console.log("beforeRouteEnter...",from,to);
return true;
},
//这个函数目前没有研究到使用方式
beforeRouteUpdate (to, from) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
console.log("beforeRouteUpdate...",from,to);
return true;
},
beforeRouteLeave (to, from) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
console.log("beforeRouteLeave...",from,to);
return true;
},