Recently, I am doing a SPA based on VUE – Router, and I want to do a unified processing for invalid routing (404) pages. This time I really did not find a specific explanation in the official document [face covering] so this article is just a way of thinking of my DIY, seek light abuse =_=
The Vue-Router matches the registered Route based on its path, loads the corresponding component if it matches, and resets (or empties) the router-view if it fails to match. So, if we don’t do anything about it, we end up with a blank page. So, can we do something about route matching?
Routing monitoring
If the current route is retrieved from this.$route in the component, you can use watch to monitor the changes to the route and see that all the changes to the route fall naturally on the root route component (e.g., app.vue).
Invalid routing detection
$route.matched $route.matched $route.matched
Interface prompt
Conditional rendering can be used. Router – View can be rendered if the route is valid, and prompt message can be rendered if the route is invalid.
Demo
App.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>
It’s up to you how friendly a 404 is.