提示:前端查漏补缺,仅代表个人观点
今天是农历八月十五中秋节,先祝看到此文章的博友中秋节快乐!!!
本文章主要讲解Vue监听路由、跳转404页面的实现和需要注意的事项,欢迎点赞评论!
// 当路由发生变化的时候执行
watch:{
$route(to,from){
console.log(to.path); // 去哪
console.log(from.path); // 从哪来
}
},
// 当路由发生变化的时候执行
watch: {
$route: {
handler: function(val, oldVal){
console.log(val);
},
// 深度观察监听
deep: true
}
}
// 当路由发生变化的时候执行
watch: {
'$route':'getPath'
},
methods: {
getPath(){
console.log(this.$route.path);
}
}
代码如下(示例):
import ErrorPage from '@/views/ErrorPage.vue'
Vue.use(Router)
const routes=[
// 其他就省略了
{
path: '/error',
name: 'ErrorPage',
component: ErrorPage,
},
]
const router = new Router({
mode: 'history',
routes: routes
})
router.beforeEach((to, from, next) => {
// 从其他地方访问是否有这个地址,没有的话就跳转去404页面
if(to.matched.length == 0){
from.path ? next({name: from.name}) : next('/error')
}
next();
});
// 错误写法,当你刷新页面或者前往其他页面,并没有打印出你想要的东西
watch: {
$route: {
handler: function (val, oldVal) {
console.log('路由信息:',val);
},
// 深度观察监听
deep: true,
}
},
// 正确写法
watch: {
$route: {
// eslint-disable-next-line no-unused-vars
handler: function (val, oldVal) {
console.log('路由信息:',val);
},
// 深度观察监听
deep: true,
immediate:true //immediate设为true后,则监听的这个对象会立即输出,也就是说一刷新页面就会在控制台输出
}
},