웹 프로젝트에서는 로그인 여부에 따라 라우팅 확인 및 해당 차단이 필요한 경우가 많습니다. 이 글은 주로 Vue에서의 경로 확인 및 그에 따른 차단 방법을 소개합니다. 관심 있는 친구들이 참고할 수 있기를 바랍니다.
먼저 로그인 상태를 저장하기 위해 vuex에 store.js를 작성합니다. 코드는 다음과 같습니다
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { user: false }, mutations: { // 登录 login (state, user) { state.user = user }, // 退出 logout (state, user) { state.user = false } } })
경로 확인:
router.beforeEach( (to, from, next) => {}
To는 여기에서 이동하려는 라우팅 방향을 나타내며, 다음은 판단 작업이며, 비어 있으면 다음 점프의 라우팅이 '/watchhouse' 또는 '/AgentMsg임을 의미합니다. ', 로그인되어 있지 않은 경우 다음 코드({path: '/login'})
if (!store.state.user && (to.path === '/watchHouse' || to.path === '/AgentMsg')) { next({ path: '/login' }) }
if (!store.state.user && (from.path === '/my') && (to.path === '/ToolCompute')) { next({ path: '/login' }) }
router.beforeEach((to, from, next) => { if (to.path === '/login') { next() } else { if (!store.state.user && (to.path === '/watchHouse' || to.path === '/AgentMsg')) { next({ path: '/login' }) } else { next() } if (!store.state.user && (from.path === '/my') && (to.path === '/ToolCompute')) { next({ path: '/login' }) } } })
이렇게 작성하면 당연히 실행 가능한 라우팅 점프입니다. 하지만 점프하고 싶은 전체 라우팅 정보를
VUE 인스턴스 앞에 라우팅 확인을 작성하면 이러한 문제가 발생하지 않습니다.
응답 차단: 예를 들어 루트 인스턴스에서는 checkLogin() 메서드를 사용하여 로그인 정보의 상태를 확인하고 로그인을 추가합니다.
var app=new Vue({ el: '#app', router, store, created(){ checkLogin().then(function (res) { if(res.data&&res.data.code==1){ store.commit('login',true); } else{ router.push('/watchHouse-css'); } }) }, template: '<App/>', components: { App } }) //响应拦截器 axios.interceptors.response.use(function(res){ //如果是未登录 if(res.data&&res.data.code==2){ app.$alert('登录用户已超时,请重新登录', '提示', { confirmButtonText: '确定', type:'warning', closeOnClickModal:false, callback: action => { router.push('/watchHouse-css') } }); } return res; },function(err){ return Promise.reject(err); })
관련 권장 사항:
vue
위 내용은 Vue의 라우팅 확인 및 해당 차단 방법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!