Meta routing meta information in vue

Routing meta information

meta

The identification information of each route is unique information of the route. Regardless of whether the meta is defined in the route, it can be accessed in the component through this.$route.meta. If it is not defined, return {}

In the component:

this.$route.meta gets the routing meta information of the component, if not defined, it returns {}

In routing:

Use router.beforeEach((to,from,next)=>{       console.log(to.meta)   }) to give each route configuration item one more meta attribute meta: { }


  


 

Use of routing meta information

According to the unique information of each route
1. Verify whether the user is logged in
2. Set the title
3. Whether to display a certain component
4. Whether the component is cached...

Verify that the user is logged in, set the title, for example:

import Vue from 'vue'
import Router from 'vue-router'

import Header from "../components/header"
import Detail from "../components/goodsDetails"
import Login from "../components/login"
import goodsList from "../components/goodsList"
Vue.use(Router)

let router = new Router({
    
    
  routes: [{
    
    
      path: '/',
      redirect: Header
    }, {
    
    
      path: '/details/:name/:price/:id',
      name: 'details',
      component: Detail,
      meta: {
    
    
        isLogin: true,
        title: "详情页"
      }
    },
    {
    
    
      path: '/login',
      name: 'login',
      component: Login,
      meta: {
    
    
        isLogin: false,
        title: "登录页"
      }
    }, {
    
    
      path: '/goodsList',
      name: "goodsList",
      component: goodsList,
      meta: {
    
    
        isLogin: false,
        title: "列表页"
      }
    }
  ]
})

//判断是否登录
router.beforeEach((to, from, next) => {
    
    
  // console.log(to);
  //设置标题
  document.title = to.meta.title;
  //判断是否登录
  let token = true;
  if (to.meta.isLogin) {
    
    
    if (token) {
    
    
      next();
    } else {
    
    
      next("/login")
    }
  }
  next();


})

export default router;

Component cache

<keep-alive>
    <router-view></router-view>
</keep-alive>
<!-- 这里是需要keepalive的 -->
<keep-alive>
    <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>

<!-- 这里不会被keepalive -->
<router-view v-if="!$route.meta.keepAlive"></router-view>
{
    
    
  path: '',
  name: '',
  component: ,
  meta: {
    
    keepAlive: true} // 这个是需要keepalive的
},
{
    
    
  path: '',
  name: '',
  component: ,
  meta: {
    
    keepAlive: false} // 这是不会被keepalive的
}

If the cached component wants to clear the data or execute the initialization method, call the activated hook function when loading the component, as follows:

activated: function () {
    
    
    this.data = '';
}

Guess you like

Origin blog.csdn.net/weixin_46034375/article/details/108966093