vue根据路由设置页面是否需要登录判断

1、在main.js中初始化项目

var Main = {
	init:function (){
		this.initVue()
		this.initBeforeEach();
	},
	initSession :async function (){
		let result = await Vue.prototype.$ajax.post('/getUserInfo');
		if(!result ||result.cd == -1 || !result.user){
			// location.href = `/login?t=****`
			return
		}
		return result.user
	},
	initBeforeEach:function (){
	  router.beforeEach(async (to, from, next) => {
			Vue.prototype.$session = await this.initSession();
			if(to.meta.needLogin && !Vue.prototype.$session){
				location.href = `/login?t=${decodeURIComponent(to.path)}`
				return
			}
	    next();
	  })
	},
	initVue:function (session){
		new Vue({
		  el: '#app',
		  router,
		  components: { App },
		  template: ''
		})
	}
}
Main.init();

2、修改router.js

export default new Router({
	mode: 'history',
  	routes: [{
		path: '/***',
		name: 'home_index',
		component: home,
		meta: {
			keepAlive: true
		  }
	},{
		path: '/***',
		name: 'mine_index',
		component: mine,
		meta:{
			needLogin:true
		}
	}]
})

 

你可能感兴趣的:(javascript,vue)