programing

nuxt 레이아웃 함수로 localStorage 데이터 가져오기

copyandpastes 2022. 7. 17. 23:03
반응형

nuxt 레이아웃 함수로 localStorage 데이터 가져오기

요.「 」 「 」 「 」 「 i말 i。이 nuxt localStorage에 되기 전에 .pages/index.vue

/pages/index.vue

<script>
export default {
  layout (context) {
    if (localStorage.getItem('AUTH_TOKEN')){
      this.$store.dispatch('changeAuthStatus', {
        authStatus: true,
        accessToken: localStorage.getItem('AUTH_TOKEN'),
        profileData: JSON.parse(localStorage.getItem('PROFILE_DATA'))
      }).then(() => {
        this.$store.dispatch('changeLoadedStatus', {
          isLoaded: true
        })
      })
    }
    else {
      this.$router.push('/auth')
    }
  }
</script>

: " " " 。localStorage is not defined

컨텍스트를 사용하여 localStorage 데이터를 가져올 수 있습니까?아니면 레이아웃 기능에서 사용할 수 있는 패키지를 제안해 주실 수 있습니까?

해결책을 찾았습니다.

Amirhossein Shahbazi가 제안한 nuxt-universal-storage 모듈을 방금 설치했습니다.그래서 방금 이렇게 했어요.

/pages/index.vue:

<script>
export default {
middleware: ['auth'],
  layout (context) {
    let currentRole = context.app.$storage.getUniversal('PROFILE_DATA')
    console.log(currentRole)
    let currentLayout = 'default'
    let defaultRoles = ['customer_support_manager', 'checker', 'storekeeper']
    let tabletRoles = ['deputy_cutting_shop']
    if (defaultRoles.includes(currentRole.role)) {
      currentLayout = 'default'
    }
    else if (tabletRoles.includes(currentRole.role)) {
      currentLayout = 'tablet'
    }
    return currentLayout
}
</script>

/middleware/auth.model:

export default function ({ redirect, app, store }) {
    // some token checkers for existing, for 401 error and for their validity
}

확실히 Nuxt는 Vue용 SSR 솔루션(Next for React와 동일)입니다.

이 경우 localStorage에 액세스할 수 없습니다.서버에서 브라우저가 실행되고 있지 않습니다!

이런 종류의 코드는 잘 작동합니다.

<script>
export default {
  layout({ store }) {
    if (process.client) {
      console.log('localStorage?', localStorage.getItem('myCat'))
      console.log('store?', store)
    }
  },
}
</script>

★★★★★★★★★★★★★★★★★★localStorage는 서버에서 사용할 수 없습니다.

써보세요.localStorage.setItem('myCat', 'Tom')하여 "" " " " " " " " " " 가 되는지 확인합니다.localStorage스토어(콘텍스트를 사용하는 것을 잊지 마세요.this을 이용하다

cookie-universal-nuxt 를 사용할 수 있습니다.

로그인 후 "AUTH_TOKEN"을 localStorage 대신 cookie로 설정할 수 있습니다.

window.$cookies.set('AUTH_TOKEN', token)

레이아웃 기능으로 액세스 할 수 있습니다.

layout (context) {
     let token=context.app.$cookies.get('AUTH_TOKEN')
}

언급URL : https://stackoverflow.com/questions/68653889/get-localstorage-data-in-nuxt-layout-function

반응형