本篇文章帶大家進行Vue學習,聊聊Vue2和Vue3中設置404界面的方法,希望對大家有所幫助!
vue頁面中,如果跳轉了不存在的路由那么,那么頁面就會出現(xiàn)白屏狀態(tài),為了解決這個問題,我們可以自己寫一個404界面,讓其跳轉過去。
在此文件中,一般存放的都是我們的路由信息,我們經常使用path:"*"來進行捕獲我們的路由,度過不存在那么我們就讓它進行跳轉至我們自定義的404頁面。
(相關資料圖)
import Vue from "vue"import Router from "vue-router"import Homepage from "@/components/Homepage"Vue.use(Router)export default new Router({ routes: [ { path: "/", component: Homepage, }, { path:"*", component:()=>import("../views/404.vue") } ]})這個頁面通常我們可以自定義,一般包括跳轉某個頁面的超鏈接或者就是定時多長時間進行跳轉。
<template> <div> <p> 頁面將在<span>{{ time }}</span>秒后自動跳轉首頁,<br> 您也可以點擊這里跳轉<a href="/">首頁</a> </p> </div></template><script>// 這里可以導入其他文件(比如:組件,工具js,第三方插件js,json文件,圖片文件等等)export default { name: "", components: { }, // 定義屬性 data() { return { time: "10", time_end: null } }, // 計算屬性,會監(jiān)聽依賴屬性值隨之變化 computed: {}, // 監(jiān)控data中的數(shù)據(jù)變化 watch: {}, // 方法集合 methods: { GoIndex() { let _t = 9 this.time_end = setInterval(() => { if (_t !== 0) { this.time = _t--; } else { this.$router.replace("/") clearTimeout(this.time_end) this.time_end = null } }, 1000) } }, // 生命周期 - 創(chuàng)建完成(可以訪問當前this實例) created() { this.GoIndex() }, // 生命周期 - 掛載完成(可以訪問DOM元素) mounted() { }, beforeCreate() { }, // 生命周期 - 創(chuàng)建之前 beforeMount() { }, // 生命周期 - 掛載之前 beforeUpdate() { }, // 生命周期 - 更新之前 updated() { }, // 生命周期 - 更新之后 beforeDestroy() { }, // 生命周期 - 銷毀之前 destroyed() { clearTimeout(this.time_end) this.time_end = null }, // 生命周期 - 銷毀完成 activated() { }, // 如果頁面有keep-alive緩存功能,這個函數(shù)會觸發(fā)}</script><style scoped>.not_found { width: 100%; height: 100%; background: url("../../static/img/404.gif") no-repeat; background-position: center; background-size: cover; p { position: absolute; top: 50%; left: 20%; transform: translate(-50%, 0); color: #fff; span{ color: orange; font-family: "仿宋"; font-size: 25px; } a { font-size: 30px; color: aqua; text-decoration: underline; } }}</style>那么實現(xiàn)的效果就如下圖所示:
404實現(xiàn)效果
為什么要分開說呢?因為在vue3中我們進行如下設置:
{ path:"*", component:()=>import("../views/404.vue") }會產生錯誤,錯誤信息:Catch all routes ("*") must now be defined using a param with a custom regexp.,意思就是:現(xiàn)在必須使用與自定義Regexp的參數(shù)定義所有路由(“*”)。
那么官方是這么說的:
// plan on directly navigating to the not-found route using its name{ path: "/:pathMatch(.*)*", name: "not-found", component: NotFound },// if you omit the last `*`, the `/` character in params will be encoded when resolving or pushing{ path: "/:pathMatch(.*)", name: "bad-not-found", component: NotFound },那么我們vue2中的index.js文件中的代碼就變成了如下:
...export default new Router({ routes: [ ..., { path:"/:pathMatch(.*)*", component:()=>import("../views/404.vue") } //或者 { path:"/:pathMatch(.*)", component:()=>import("../views/404.vue") } ]})(學習視頻分享:vuejs入門教程、編程基礎視頻)
以上就是聊聊Vue2和Vue3中怎么設置404界面的詳細內容,更多請關注php中文網其它相關文章!