vue-router 实现无效路由(404)的友好提示

<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

&lt;template&gt;
  &lt;p v-if="invalidRoute"&gt;404&lt;/p&gt;
  &lt;router-view v-else&gt;&lt;/router-view&gt;
&lt;/template&gt;

&lt;script type="text/babel"&gt;
  export default {
    name: 'App',
    computed: {
      invalidRoute () {
        return !this.$route.matched || this.$route.matched.length === 0;
      }
    }
  };
&lt;/script&gt;

<blockquote>至于404要多友好就看本身了[惹不起]</blockquote>vue-router

原文地址:http://www.javashuo.com/article/p-xmvjhgpy-es.htmlsegmentfault

相关文章
相关标签/搜索