반응형
백엔드 응답에 따라 먼저 Vue 앱을 초기화하려면 어떻게 해야 합니까?
앱에서 가장 먼저 코드를 실행하고 싶습니다.그 코드는 Back-end로 요청을 전송하고 스토어를 업데이트합니다.그 부분은 루트 가드가 의존하기 때문에 먼저 실행해야 하는데, 어떻게 하면 될까요?
코드 예시
사용자 정보 및 설정 가져오기
async init() {
await AuthService.initCSRF();
await AuthService.getUser().then((res) => {
if (res.data && res.data.user) {
this.loginLocally(res.data.user);
} else {
this.logoutLocally();
}
});
}
인증 가드
export function isLoggedIn(to, from, next) {
console.log('Checked', store.state.auth.isLoggedIn);
if (store.state.auth.isLoggedIn) {
next();
return;
}
next({ name: 'login' })
}
예전 프로젝트에서 이런 걸 했어요.뭔가 알아냈으면 좋겠어
app.module
import App from './components/App.vue'
store.dispatch('auth/attempt', sessionStorage.getItem('token')).then(() =>{
new Vue({
el: '#app',
router,
store,
render: h => h(App),
});
});
여기서는 앱을 렌더링하기 전에 로컬 스토리지에 저장된 토큰을 검증합니다.
제 Vuex 동작은 이런 거였어요
async signIn({dispatch}, credentials) {
let response = await axios.post("auth/signin", credentials);
await dispatch('attempt', response.data.token)
},
async attempt({commit, state}, token) {
if (token) {
await commit('SET_TOKEN', token);
}
if (!state.token) {
return;
}
try {
let response = await axios.get('auth/me');
commit('SET_USER', response.data)
} catch (e) {
commit('SET_TOKEN', null);
commit('SET_USER', null);
}
},
async signOut({commit}) {
axios.post('auth/signout').then(() => {
commit('SET_TOKEN', null);
commit('SET_USER', null);
});
}
가입자를 사용하여 돌연변이를 듣고 요청 헤더에 토큰을 추가하거나 제거합니다.
import store from '../store'
store.subscribe((mutation) => {
if (mutation.type === 'auth/SET_TOKEN') {
if (mutation.payload) {
axios.defaults.headers.common['Authorization'] = `Bearer ${mutation.payload}`;
sessionStorage.setItem('token', mutation.payload);
} else {
axios.defaults.headers.common['Authorization'] = null;
sessionStorage.removeItem('token');
}
}
});
마지막으로 핸들 토큰 유효기간용 악시오스 인터셉터입니다.
import router from '../plugins/router'
import store from '../store'
import axios from "axios";
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
if (error.response.status) {
if (error.response.status === 401) {
if (router.currentRoute.name !== 'landing') {
store.dispatch('auth/clearToken').then(() => {
router.replace({
name: 'landing'
});
}).finally(() => {
swal.fire(
'Your Session is Expired',
'Please sign in again!',
'error'
)
});
}
}
}
return Promise.reject(error);
});
초기화 약속은 호출 전에 기다릴 수 있습니다..mount(...)문제는 Vue 라우터가 어플리케이션과 별도로 시작되어 이러한 방식으로 지연되지 않는다는 것입니다.
초기화 프로세스에 의존하는 라우터의 경우 라우터의 기동을 지연시키는 방법은 다른 프로세스에 앞서 트리거되는 라우터 후크에서 약속을 기다리는 것입니다.
const initPromise = init();
...
router.beforeEach(async (to, from, next) => {
await initPromise;
next();
});
언급URL : https://stackoverflow.com/questions/70547631/how-to-initialize-the-vue-app-depending-on-back-end-response-first
반응형
'programing' 카테고리의 다른 글
| Java의 해시맵과 해시테이블의 차이점은 무엇입니까? (0) | 2022.08.25 |
|---|---|
| prefix 연산자와 postfix 연산자의 차이점은 무엇입니까? (0) | 2022.08.25 |
| vue.js 단위의 각 ng-container 당량 (0) | 2022.08.25 |
| Larabel Vue.js와 CKeditor 4 및 CKFinder 3의 통합(파일 매니저) (0) | 2022.08.25 |
| vuejs 및 웹 팩에 글꼴 파일을 로드하려면 어떻게 해야 합니까? (0) | 2022.08.25 |