這篇文章主要講解了“Vue2和Vue3中如何設置404界面”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Vue2和Vue3中如何設置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')
}
]
})
注意:這個path一定要寫在最外面。
這個頁面通常我們可以自定義,一般包括跳轉某個頁面的超鏈接或者就是定時多長時間進行跳轉。
<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
}
},
// 計算屬性,會監聽依賴屬性值隨之變化
computed: {},
// 監控data中的數據變化
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)
}
},
// 生命周期 - 創建完成(可以訪問當前this實例)
created() {
this.GoIndex()
},
// 生命周期 - 掛載完成(可以訪問DOM元素)
mounted() {
},
beforeCreate() { }, // 生命周期 - 創建之前
beforeMount() { }, // 生命周期 - 掛載之前
beforeUpdate() { }, // 生命周期 - 更新之前
updated() { }, // 生命周期 - 更新之后
beforeDestroy() { }, // 生命周期 - 銷毀之前
destroyed() {
clearTimeout(this.time_end)
this.time_end = null
}, // 生命周期 - 銷毀完成
activated() { }, // 如果頁面有keep-alive緩存功能,這個函數會觸發
}
</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>
為什么要分開說呢?因為在vue3中我們進行如下設置:
{
path:'*',
component:()=>import('../views/404.vue')
}
會產生錯誤,錯誤信息:Catch all routes ("*") must now be defined using a param with a custom regexp.,意思就是:現在必須使用與自定義Regexp的參數定義所有路由(“*”)。
那么官方是這么說的:
// 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')
}
]
})
感謝各位的閱讀,以上就是“Vue2和Vue3中如何設置404界面”的內容了,經過本文的學習后,相信大家對Vue2和Vue3中如何設置404界面這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。