前言
今日给自己项目添加404页面时,踩了一点坑,分享给大家。
正文
<div class="_404"><h2 class="m-0">抱歉,页面未找到,<span>{{countDown}}</span>s后自动跳转到<a href="javascript:;" @click="goHome">首页</a></h2><img src="../assets/404.jpg" alt="页面未找到"></div><style>body {background-color: #dceebc;}._404 {width: 30%;margin: 5rem auto;}._404 img {width: 30rem;}._404 a {color: #010101;}._404 a:hover {color: skyblue;}
</style>
页面结构很简单,一点提示信息和一张顺眼的图片即可。
<script>export default {name: "NF404",data() {return {countDown: 5}},methods: {goHome() {this.$router.push('/main/home')}},created() {setInterval(() => {this.countDown > 0 ? this.countDown-- : this.$router.push('/main/home')}, 1000)}}
</script>
脚本这里,逻辑为倒计时后自动跳转至首页,或者主动点击链接也可以跳转。
- 结果发现,第一次进入404页面,是很成功的,但是再次进入的话,就会直接跳转至主页,没有倒计时。
- 第一时间我是觉得是因为vue组件从缓存里加载的问题,所以
created
函数只在第一次触发。于是在created
函数中加入了alert()
,发现每次进入404页面,确实是重新创建了。也就是说,vue router变换时,默认是会销毁离开的组件的。 - 那么我又想到可能是
setInterval()
的问题,可能是没有及时清除的原因,将代码修改之后,成功运行。
<script>export default {name: "NF404",data() {return {countDown: 5,timer: null}},methods: {goHome() {this.$router.push('/main/home')clearInterval(this.timer)}},created() {this.timer = setInterval(() => {this.countDown > 0 ? this.countDown-- : this.goHome()}, 1000)}}
</script>
22/05/10更新
在vue2中,捕获404路径的写法是:
{path: "*",name: "NotFound",component: () => import("@/views/common/not-found/NotFound.vue"),
}
而在vue3中,vue-router禁用了这种写法,改为:
{path: "/:pathMatch(.*)",name: "NotFound",component: () => import("@/views/common/not-found/NotFound.vue"),
}
结语
在vue组件中使用计时器的时候,一定要记得及时清除!
如果对你有帮助的话,请点一个赞吧