导航守卫 登录拦截

主要利用beforeEach

在router/index.js下

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//引入组件
import Home from './../components/home'
import Main from './../components/main'
import Hot from './../components/hot'
import Other from './../components/other'
import Login from './../components/login'
var router = new VueRouter({
    routes:[
        {
            path:'/home',
            component:Home,
            name:Home
        },
        {
            path:'/main',
            component:Main,
            name:Main
        },
        {
            path:'/hot',
            component:Hot,
            name:Hot
        },
        {
            path:'/other',
            component:Other,
            name:Other
        },
        {
            path:'/login',
            component:Login,
            name:Login
        },
        {
            path:'/',
            redirect:'/home'
        }
    ]
})
//导航守卫 全局前置守卫
//to: 要进入的路由目标(去哪里)
//from: 当前导航正要离开的路由(从哪儿来)
//next : 一定要调用该方法来 resolve 这个钩子  (执行)
 router.beforeEach((to, from, next)=>{
  if(to.path !== '/login'){
    if(localStorage.getItem("key")){
        next()
    }else{
        next('/login')
    }
  }else{
      next()
  }
})
export default router

其他主要代码如下

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router/index'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  router
}).$mount('#app')

App.vue






components/tab.vue



components/home.vue



其他均与home类似  这里就省略了

你可能感兴趣的:(前端学习笔记)