Programing

Vue에서 구성 요소 로드를 중지하고 리디렉션하는 방법

c10106 2022. 3. 27. 13:48
반응형

Vue에서 구성 요소 로드를 중지하고 리디렉션하는 방법

로그인하지 않은 사용자가 액세스할 수 없는 구성 요소가 있다.나는 이 논리를 에 적용했다.beforeCreate훅. 문제는 이렇게 해서 부품이 계속 로딩되는 것을 막을 수 없다는 것이다. 내가 원했던 것이다.

이건 내 암호야

<script>
    export default {
        beforeCreate: function () {
            if (this.$root.auth.user === null) {
                this.$router.push({ name: 'auth.login' })
            }
        },

        mounted: function () {
            // some code that SHOULD NOT be processed
            // if the user isn't authenticated
        }
    }
</script>

내가 뭘 잘못하고 있는 거지?

foreCreate 기능을라우터자체로 이동해야 한다.여기 내 Auth catch

router.beforeEach(
  (to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
      // if route requires auth and user isn't authenticated
      if (!store.state.Authentication.authenticated) {
        let query = to.fullPath.match(/^\/$/) ? {} : { redirect: to.fullPath }
        next(
          {
            path: '/login',
            query: query
          }
        )
        return
      }
    }
    next()
  }
)

내 경로 정의를 사용하여 인증 및 게스트 배치를 처리할 수 있다.

{
  path: '/',
  component: load('Template'),
  children: [
    { path: '', component: load('Dashboard'), name: 'Dashboard' }
  ],
  meta: { requiresAuth: true }
},
{
  path: '/login',
  component: load('Authentication/Login'),
  name: 'login'
},

Vue에 의해 구성요소가 초기화되기 전에 호출되는 라우터에 그것을 가지고 있으면, 이것은 구성요소 수준 이벤트의 처리를 중지할 것이다.

참조URL: https://stackoverflow.com/questions/46288589/how-to-stop-component-loading-and-redirect-in-vue

반응형