Easy to understand Vue router

<head>
    <meta charset="UTF-8">
    <title>vuejs Course</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <style>
        .router-link-active{
            font-size: 20px;
            color:#f60;
        }
    </style>
    <script src="vue.js"></script>
    <script src="bower_components/vue-router/dist/vue-router.min.js"></script>
</head>
<body>
    <div id="box">

        <div>
            <router-link to="/home">homepage</router-link>
            <router-link to="/user">user</router-link>
        </div>
        <div>
            <router-view></router-view>
        </div>
    </div>

    <template id="home">

        <div>
            <h3>I am user information</h3>
            <ul>
                <li><router-link to="/user/strive/age/10">Strive</router-link></li>
                <li><router-link to="/user/blue/age/80">Blue</router-link></li>
                <li><router-link to="/user/eric/age/70">Eric</router-link></li>
            </ul>
            <div>
                <router-view></router-view>
            </div>
        </div>

    </template>

    <script>
        //assembly
        var Home={
            template:'<h3>I am the home page.</h3>'
        };
        var User={
            template:'#home'
        };
        var UserDetail={
            template:'<div>{{$route.params}}</div>'
        };

        //Configuration routing
        const routes=[
            {path:'/home', component:Home},
            {
                path:'/user',
                component:User,
                children:[
                    {path:':username/age/:age', component:UserDetail}
                ]
            },
            {path:'*', redirect:'/home'}  //404
        ];

        //Generate route instance
        const router=new VueRouter({
            routes
        });


        //Hang up to vue at last
        new Vue({
            router
        }).$mount('#box');
    </script>
</body>

router Description:

  Router Simple explanation

  #Use program jump (like angularjs's $state.go)
  this.$router.push(location, onComplete?, onAbort?);

  #Return to the history page similar to history.go(-1)
  this.$router.go(-1)

  //router.back(),router.forward()

  #Page link usage
  <router-link :to="ch.url">{{ch.text}}</router-link>

  //Or li > A that's it

  <router-link tag="li" to="/home" active-class="active" :key="index">
    <a>Home</a>
  </router-link>

watch monitoring router
*In Sidebar component, add watch to judge each route jump

watch: {
  $route() {
    // Check whether the first level menu link
    this.checkMenuActived(this.$route.path);
  }
}
  • Add checkMenuActived method to control related implementation

    methods: {
    ...
    checkMenuActived(path) {
    // Traverse all the first level menus
    this.menus.forEach(item => {
      // If it is not the current route, the activation status will be cancelled
      if (item.href && item.href !== path) {
        item.class = '';
      }
    });
    }
    } 
    • The routing object, that is, $router, will be injected into each component. It can be used to obtain some information
      $route.path the path of the current routing object, such as' / view/a '
      $rotue.params key value pair information about dynamic fragments (such as / user/:username), such as {Username: 'paolino'}
      $route.query request parameter, for example, / foo?user=1 gets query.user = 1
       Router and component information of $route.router
       $route.matched array, which contains configuration parameter objects corresponding to all fragments contained in the currently matched path.
      $route.name current path name
  • At the beginning of every route navigation, check whether the user is logged in

router.beforeEach(({meta, path}, from, next) => {  

  const {auth = true} = meta      // meta The representative is to Medium meta Object, path The representative is to Medium path object

  var isLogin = Boolean(store.state.user.id)    // trueThe user is logged in, falseUser not logged in 
  
  if (auth  &&  !isLogin  &&  path !== '/login') {   // auth The delegate needs to pass user authentication. The default istrue,Representatives need to be verified, falseTo avoid inspection
    return next({ path: '/login' })   //  Jump to login page
  }


  next()   // Go to the next hook function
})


//It has three parameters:

to: (Route Routing object)  Destination routing object to enter       toObject: path   params  query   hash   fullPath    matched   name    meta(staymatchedNext, but this example can be used directly)

from: (Route Routing object)  Route the current navigation is about to leave

next: (Function function)   Be sure to call this method resolve This hook.
  • Several ways of js route jump
// Character string
this.router.push('home')

// object
this.$router.push({path: '/login?url=' + this.$route.path});

// Named route
router.push({ name: 'user', params: { userId: 123 }})

// With query parameter, change to / backend/order?selected=2
this.$router.push({path: '/backend/order', query: {selected: "2"}});

// Set query parameters
this.$http.post('v1/user/select-stage', {stage: stage})
      .then(({data: {code, content}}) => {
            if (code === 0) {
                // object
                this.$router.push({path: '/home'});
            }else if(code === 10){
                // With query parameter, / login?stage=stage
                this.$router.push({path: '/login', query:{stage: stage}});
           }
});

// Design query parameter object
let queryData = {};
if (this.$route.query.stage) {
    queryData.stage = this.$route.query.stage;
}
if (this.$route.query.url) {
    queryData.url = this.$route.query.url;
}
this.$router.push({path: '/my/profile', query: queryData});

Keywords: Vue Mobile AngularJS

Added by hazy on Sat, 28 Mar 2020 17:53:05 +0200