<p>最近在作一個基於<code>vue-router</code>的<code>SPA</code>,想對無效路由(404)頁面作下統一處理。<br>此次我真的沒有在<a href="https://router.vuejs.org/en/" rel="nofollow noreferrer">官方文檔</a>找到具體的說明[捂臉]<br>因此本文僅是我DIY的一個思路,求輕虐=_=</p> <p>在個人理解中,<code>vue-router</code>是根據<code>path</code>去匹配註冊的<code>route</code>,匹配到則加載對應的組件,匹配不到則重置(或者說清空)對應的<code>router-view</code>。<br>因此,咱們不作處理的話,最終頁面展現的是一片空白。<br>那麼,咱們是否是能夠在路由匹配上作文章呢?</p> <h3>路由監測</h3> <p>在組件中,能夠從<code>this.$route</code>獲取當前路由,那麼就能夠使用<code>watch</code>監測路由的變化,監測全部路由變化天然而然的落在<strong>根路由組件</strong>(如:<code>App.vue</code>)上面了。</p> <h3>無效路由檢測</h3> <p><code>$route.matched</code>包含了當前路由的匹配結果,若是爲空則說明當前路由無效。</p> <h3>界面提示</h3> <p>可以使用條件渲染,路由有效則渲染<code>router-view</code>,路由無效則渲染提示信息。</p> <h3>Demo</h3> <p><code>App.vue</code></p>vue
<template> <p v-if="invalidRoute">404</p> <router-view v-else></router-view> </template> <script type="text/babel"> export default { name: 'App', computed: { invalidRoute () { return !this.$route.matched || this.$route.matched.length === 0; } } }; </script>
<blockquote>至於404要多友好就看本身了[惹不起]</blockquote>vue-router
原文地址:http://www.javashuo.com/article/p-xmvjhgpy-es.htmlsegmentfault