路由vue-router

之前构建说了有个目录是路由配置,现在说些项目里用到的路由配置吧

首先肯定是引入router(在构建项目的时候已经安装了vue-router):  

    在main.js加入这句话     import router from './router';

我的路由页面 分三部分,分别是:

    1.各个页面的路由配置:例

            {path: '/Dir',
             name: '首页',
             component: resolve => require(['@/components/page/home/Dir'], resolve),meta:{requireAuth: true }
 
                    meta设置是否需要导航首位
              resolve=>require这样写可以去调用相应页面的时候去加载相应页面(解决首次加载慢)
    2.项目的路由类别(hash/history)
        
            const router = new Router({
                     mode: 'hash',
                     routes});

            想了解hash和history的区别,点击这里 

    3.导航守卫:     

     router.beforeEach((to, from, next) => {
        if (to.meta.requireAuth) {                 //判断页面地址是否需要守卫
          if (sessionStorage.getItem('token')) { 
            next()
          } else {
            next({           //进入守卫,不满足跳回登陆页
              path: '/Login',
              })}} else {
                next()}})
 
另:附上router跳转
  标签:<router-link to="Dir">Home</router-link>
  js:  this.$router.push({path: '/ClassList'})
  在vue项目打开新窗口(window.open('url'))
 

最后奉上完整代码,以供参考

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

Vue.use(Router)

const routes = [
{
path: '/',
redirect: '/Login'
},
{
path: '/Login',
name: '登陆',
component: resolve => require(['@/components/page/login/Login'], resolve),
}, {
path: '/',
component: resolve => require(['@/components/common/Home'], resolve),
name: '页面结构',
meta: {
requireAuth: true,
},
children: [
{
path: '/Dir',
name: '首页',
component: resolve => require(['@/components/page/home/Dir'], resolve),meta:{requireAuth: true }
}, {
path: '/incomeOverview',
name: '收入/概况',
component: resolve => require(['@/components/page/income/Overview'], resolve),meta:{requireAuth: true }
}
]
}]

const router = new Router({
mode: 'hash',
routes
});


router.beforeEach((to, from, next) => {
if (to.meta.requireAuth) {
//这里放入我们的存的token
if (sessionStorage.getItem('token')) {
next()
} else {
next({
path: '/Login',
})
}
} else {
next()
}
})

export default router
    

posted on 2018-01-16 14:20  yanggg  阅读(173)  评论(0编辑  收藏  举报

导航