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
'programing' 카테고리의 다른 글
IntelliJ IDEA를 중지하여 폼을 새로고침할 때마다 Java 언어 수준을 전환합니다(또는 기본 프로젝트 언어 수준을 변경). (0) | 2022.07.17 |
---|---|
Vue / Vuex구성 요소에서 Vuex 저장소 속성에 액세스할 수 없음 (0) | 2022.07.17 |
초보자에게 C 포인터(선언 대 단항 연산자)를 어떻게 설명합니까? (0) | 2022.07.17 |
기본 Vue 인스턴스, Vuex 또는 mixin을 사용할 시기를 선택하십시오. (0) | 2022.07.17 |
C는 왜 이렇게 빠를까요?다른 언어는 왜 그렇게 빠르거나 빠르지 않을까요? (0) | 2022.07.17 |