VueRouter Basic tutorial series 🎉
Routing meta information
First, to standardize the terminology, we call each configuration item in a Routing configuration object (Routes) a “routing record”.
Routing records can be nested by children, so when a route is matched, it may match multiple routing records, which are saved as a $Route object in the $Route. matched array.
You can define the meta information of a route through the meta attribute of the route record. Routing meta-information allows you to attach custom data to a route, for example:
- Id of permission verification.
- The transition name of the routing component.
- Configuration of keep-alive for routing components.
We can access the meta information data of the route in the navigation guard or in the route object.
const UsersDetail = {
// Through the route object $route
template: '<div>{{$route.meta.isRequireAuth}}</div>'};const routes = [
{
path: '/users/:id'.component: UsersDetail,
meta: { isRequireAuth: true}}];const router = VueRouter.createRouter({
history:VueRouter.createWebHashHisotry(),
routes
});
router.beforeEach((to, from) = >{
// Navigate through the route guard
if(to.meta.isRequireAuth && ! auth.isLoggedIn() && to.path.indexOf('login') = = = -1) {return '/login'; }})Copy the code
TypeScript – Module supplement
In TypeScript we need to use module supplements to extend the RouteMeta interface’s type declarations to help TypeScript type check custom meta members.
import 'vue-router';
declare module 'vue-router' {
interfaceRouteMeta { isRequireAuth? :boolean}}Copy the code