主要利用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
<template>
<div id="app">
<Tab />
<router-view></router-view>
</div>
</template>
<script>
import Tab from './components/tab'
export default {
name: 'app',
components:{
Tab
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
components/tab.vue
<template>
<div class="tab">
<span @click="tabPath('/home')" :class="{active:$route.path.includes('/home')}">主页</span>
<span @click="tabPath('/main')" :class="{active:$route.path.includes('/main')}">主要</span>
<span @click="tabPath('/hot')" :class="{active:$route.path.includes('/hot')}">最热门</span>
<span @click="tabPath('/other')" :class="{'active':$route.path.includes('other')}">其他</span>
<span @click="tabPath('/login')" :class="{'active':$route.path.includes('login')}">登录</span>
</div>
</template>
<style scoped>
span{
margin: 2px 4px;
background: #cccccc;
cursor: pointer;
}
.active{
color: red
}
</style>
<script>
export default {
name:'Tab',
methods:{
tabPath(path){
this.$router.push(path)
}
}
}
</script>
components/home.vue
<template>
<div class="home">
我是主页
</div>
</template>
<style scoped>
.home{
color: aqua
}
</style>
<script>
export default {
name:'Home'
}
</script>
其他均与home类似 这里就省略了