Nuxt.js의 서버 측과 Vuex 스토어 동기화
문제
Nuxt 미들웨어 이하
const inspectAuthentication: Middleware = async (): Promise<void> => {
await AuthenticationService.getInstance().inspectAuthentication();
};
각 페이지의 HTML을 반환하기 전에 서버 측에서 실행되고 있으며 체크가 사용자 인증되었습니다.되어 있는 는, 「」가 됩니다.CurrentAuthenticatedUser
Vuex 모: :
import {
VuexModule,
getModule as getVuexModule,
Module as VuexModuleConfiguration,
VuexAction,
VuexMutation
} from "nuxt-property-decorator";
@VuexModuleConfiguration({
name: "AuthenticationService",
store,
namespaced: true,
stateFactory: true,
dynamic: true
})
export default class AuthenticationService extends VuexModule {
public static getInstance(): AuthenticationService {
return getVuexModule(AuthenticationService);
}
private _currentAuthenticatedUser: CurrentAuthenticatedUser | null = null;
public get currentAuthenticatedUser(): CurrentAuthenticatedUser | null {
return this._currentAuthenticatedUser;
}
@VuexAction({ rawError: true })
public async inspectAuthentication(): Promise<boolean> {
// This condition is always falsy after page reloading
if (this.isAuthenticationInspectionSuccessfullyComplete) {
return isNotNull(this._currentAuthenticatedUser);
}
this.onAuthenticationInspectionStarted();
// The is no local storage on server side; use @nuxtjs/universal-storage instead
const accessToken: string | null = DependenciesInjector.universalStorageService.
getItem(AuthenticationService.ACCESS_TOKEN_KEY_IN_LOCAL_STORAGE);
if (isNull(accessToken)) {
this.completeAuthenticationInspection();
return false;
}
let currentAuthenticatedUser: CurrentAuthenticatedUser | null;
try {
currentAuthenticatedUser = await DependenciesInjector.gateways.authentication.getCurrentAuthenticatedUser(accessToken);
} catch (error: unknown) {
this.onAuthenticationInspectionFailed();
// error wrapping / rethrowing
}
if (isNull(currentAuthenticatedUser)) {
this.completeAuthenticationInspection();
return false;
}
this.completeAuthenticationInspection(currentAuthenticatedUser);
return true;
}
@VuexMutation
private completeAuthenticationInspection(currentAuthenticatedUser?: CurrentAuthenticatedUser): void {
if (isNotUndefined(currentAuthenticatedUser)) {
this._currentAuthenticatedUser = currentAuthenticatedUser;
DependenciesInjector.universalStorageService.setItem(
AuthenticationService.ACCESS_TOKEN_KEY_IN_LOCAL_STORAGE, currentAuthenticatedUser.accessToken
);
}
// ...
}
}
에서는 「」를 취득하려고 , 「」를 취득하려고 합니다.AuthenticationService.getInstance().currentAuthenticatedUser
될 거예요.null
!가 ! Nuxt.js를 AuthenticationService
이치노
대상
AuthenticationService
.AuthenticationService.getInstance().currentAuthenticatedUser
페이지를 새로고침한 후에도 비메모리여야 합니다.
서버측에서 Vuex 스토어 전체를 동기화할 필요는 없습니다(예를 들어 클라이언트측에서만 모듈을 담당하는 부동 알림 바가 필요합니다).단, 선택적인 방법론이 개발되지 않은 경우에는 적어도 Vuex 스토어 전체를 동기화하는 것으로 충분합니다.
Nuxt Auth 모듈과 같은 인증에 라이브러리나 Nuxt 모듈을 추천하지 마십시오.Vuex 스토어와 서버의 동기화가 인증에 최적인 Nuxt 모듈에 대한 것이 아닙니다.또, 클라이언트와 서버간의 vuex 스토어 동기화는, 인증에만 사용하는 것이 아닙니다.
갱신하다
preserveState
시행
불행하게도,
import { store } from "~/Store";
import { VuexModule, Module as VuexModuleConfiguration } from "nuxt-property-decorator";
@VuexModuleConfiguration({
name: "AuthenticationService",
store,
namespaced: true,
stateFactory: true,
dynamic: true,
preserveState: true /* New */
})
export default class AuthenticationService extends VuexModule {}
원인들
Cannot read property '_currentAuthenticatedUser' of undefined
서버 측에서 오류가 발생했습니다.
이 에러는
@VuexAction({ rawError: true })
public async inspectAuthentication(): Promise<boolean> {
if (this.isAuthenticationInspectionSuccessfullyComplete) {
// HERE ⇩
return isNotNull(this._currentAuthenticatedUser);
}
}
this
해야 할 이것은 큰 대상입니다. 이치노
{
store: Store {
_committing: false,
// === ✏ All actual action here
_actions: [Object: null prototype] {
'AuthenticationService/inspectAuthentication': [Array],
'AuthenticationService/signIn': [Array],
'AuthenticationService/applySignUp': [Array],
// ...
// === ✏ Some mutations ...
onAuthenticationInspectionStarted: [Function (anonymous)],
completeAuthenticationInspection: [Function (anonymous)],
// ...
context: {
dispatch: [Function (anonymous)],
commit: [Function (anonymous)],
getters: {
currentAuthenticatedUser: [Getter],
isAuthenticationInspectionSuccessfullyComplete: [Getter]
},
// === ✏ The state in undefined!
state: undefined
}
}
vuex 스토어를 초기화하는 방법을 알려줘야 할 것 같습니다.다이내믹 모듈에 유효한 Nuxt 메서드는 다음과 같습니다.
// store/index.ts
import Vue from "vue";
import Vuex, { Store } from "vuex";
Vue.use(Vuex);
export const store: Store<unknown> = new Vuex.Store<unknown>({});
nuxtServerInit
시행
문제는 입니다.통합하는 방법nuxtServerInit
위의 스토어 초기화 방법에 대해 알려주세요.이 질문에 답하려면 Vuex 및 vuex-module-decorator가 필요합니다.아래store/index.ts
, . . . . . . . .nuxtServerInit
호출되지 않습니다.
import Vue from "vue";
import Vuex, { Store } from "vuex";
Vue.use(Vuex);
export const store: Store<unknown> = new Vuex.Store<unknown>({
actions: {
nuxtServerInit(blackbox: unknown): void {
console.log("----------------");
console.log(blackbox);
}
}
});
나는 이 문제를 다른 질문으로 끌어냈다.
이것은 SSR를 사용할 때의 주요 과제 중 하나입니다.서버로부터 정적 HTML로 응답을 받은 후 클라이언트에서 Hydration이라는 프로세스가 발생합니다.(자세한 내용은 이 Vue SSR 가이드를 참조하십시오.)
Nuxt가 구축되는 방식과 SSR/클라이언트 관계가 하이드레이션에 대해 작동하는 방식 때문에 서버가 애플리케이션의 스냅샷을 렌더링하지만 클라이언트가 앱을 마운트하기 전에 비동기 데이터를 사용할 수 없어 다른 저장소 상태를 렌더링하여 하이드레이션이 중단됩니다.
Nuxt 및 Next(For React)와 같은 프레임워크는 Auth를 위해 자체 컴포넌트를 구현하고 있으며, 기타 많은 컴포넌트를 구현하여 올바른 수화 처리를 위한 수동 조정 프로세스를 처리하는 것입니다.
따라서 Nuxt 내장 인증 모듈을 사용하지 않고 이를 수정하는 방법에 대해 자세히 알아보려면 몇 가지 유의해야 할 사항이 있습니다.
- 그 때
serverPrefetch
서버측에서 호출되는 메서드.이 메서드는 약속이 해결될 때까지 기다렸다가 클라이언트에 전송하여 렌더링합니다. - 컴포넌트 렌더링 외에 서버에서 클라이언트로 전송되는 콘텍스트가 있습니다.이 콘텍스트는 다음 명령어를 사용하여 주입할 수 있습니다.
rendered
후크(앱이 렌더링을 완료했을 때 호출됩니다.따라서 클라이언트에게 스토어 상태를 돌려보내 하이드레이션 프로세스에서 재사용할 수 있는 적절한 타이밍입니다. - 매장 자체에서, 만약 당신이 그것을 사용하고 있다면
registerModule
, Atribute를 서포트하고 있습니다.preserveState
서버에 의해 주입된 상태를 유지하는 역할을 합니다.
이러한 부품의 작업 방법의 예에 대해서는, 이 페이지의 코드를 확인해 주세요.
마지막으로 사용자 인증 과제와 관련된 다른 옵션은nuxtServerInit
Nuxt 문서에 설명된 대로 나중에 클라이언트에 직접 전달되기 때문에 이 인증 처리를 실행하기 위한 작업을 저장합니다.
갱신
같은 페이지에서 docs는 nextServerInit의 첫 번째 인수가 nextServerInit의 첫 번째 인수가context
즉, 이 기능을 통해store
예를 들어, 거기서부터.
또한 언급해야 할 중요한 한 가지 포인트는 원래 질문에서 서드파티 립을 원하지 않는다고 언급했지만 이미 테이블에 많은 복잡성을 가져오는 립을 사용하고 있다는 것입니다.nuxt-property-decorator
따라서 프레임워크 사용 시처럼 복잡한 SSR뿐만 아니라 순수 Vue를 사용하지 않고 순수 TS Nuxt를 사용하지 않고 스토어용 데코레이터로 복잡함을 더하고 있습니다.
내가 왜 그걸 언급하고 있지?lib 문제에 대해 간단히 살펴보기 때문에 같은 문제를 안고 있는 다른 사용자가 있습니다.this
올바르게 동작합니다.
Nuxt(Vue)와 Next(React)를 모두 사용한 사람의 배경에서 나온 말인데, 여러 가지 작업을 시도하기 전에 복잡성을 줄이도록 하는 것이 좋습니다. 저는 이 앱 없이 nuxt-property-decorator
이것이 바로 사용할 수 있는 스토어 구현과 함께 작동하는지 확인하기 위해 SSR 복잡성을 지원할 준비가 완전히 되지 않은 lib에서 발생한 버그가 아닌지 확인합니다.
언급URL : https://stackoverflow.com/questions/69340160/synchronize-vuex-store-with-server-side-in-nuxt-js
'programing' 카테고리의 다른 글
타임아웃으로 Input Stream에서 읽을 수 있습니까? (0) | 2022.05.31 |
---|---|
Vue 라우터 - 매개 변수가 전달되지 않음 (0) | 2022.05.31 |
vue 구성 요소에서 setInterval을 사용하는 방법 (0) | 2022.05.31 |
Java에서 & & &의 차이점은 무엇입니까? (0) | 2022.05.31 |
npm 설치 미달 의존 관계 (0) | 2022.05.31 |