반응형
Vuex 작업 및 구성 요소에서 경로 변경
사용자가 로그인 폼을 통해 내 앱에 정상적으로 로그인한 후.프로필이 있는지 확인하고 싶어요.그렇다면 뉴스 페이지로 보내고 싶습니다.설정이 없는 경우는, 「설정」페이지로 리다이렉트 합니다.Vuex를 사용하여 이 작업을 수행하는 방법
몇 가지 옵션이 있습니다.
1. 리다이렉트를 담당하는 컴포넌트(불편한 기분)
Login.vue
handleFormSubmit () {
this.$store.dispatch('loginFormSubmit', formData)
.then(() => {
// This feels a bit gross
this.$store.dispatch('getUserProfile')
.then(() => this.$router.push('/news'))
.catch(() => this.$router.push('/settings'))
})
.catch(() => {
this.loginError = true
})
}
2. 행동에 대한 책임을 지게 되나요?
user-actions.displaces
export const getUserProfile = ({commit}) => {
commit(types.USER_PROFILE_REQUEST)
const options = {
url: `${API_URL}/profile`,
method: 'GET'
}
return request(options)
.then((profileSettings) => {
// Would I change the router to News here??
commit(types.USER_PROFILE_SUCCESS, profileSettings)
return Promise.resolve(profileSettings)
})
.catch((error) => {
// Would I change the router to Settings here??
commit(types.UI_MENU_HIDE)
return Promise.reject(error)
})
}
export const loginFormSubmit = ({dispatch, commit}, { email, password }) => {
console.log(email, password)
commit(types.USER_LOGIN_REQUEST)
const options = {
url: `${API_URL}/token`
}
return request(options)
.then((response) => {
dispatch('getUserProfile')
commit(types.USER_LOGIN_SUCCESS, response.token)
return Promise.resolve(response.token)
})
.catch((error) => {
commit(types.USER_LOGIN_FAILURE, error)
return Promise.reject(error)
})
}
3. 가드와 함께 라우터에 보관해야 하지 않을까요?
Login.vue
handleFormSubmit () {
this.$store.dispatch('loginFormSubmit', formData)
.then(() => this.$router.push('/news'))
.catch(() => {
this.loginError = true
})
}
다음으로 라우터에서 다음을 수행합니다.
const routes = [
{
path: 'news',
alias: '',
component: NewsView,
name: 'News',
meta: { description: 'News feed page' },
beforeEnter: (to, from, next) => {
store.dispatch('getUserProfile')
- .then((resp) => {
- // Profile set
- next()
- })
- .catch(() => {
- // No profile set
- next({ name: 'settings' })
- })
}
},
]
4. 매장 변경을 듣고 경로를 변경한다.
computed: {
isAuthenticated () {
return this.$store.getters.isAuthenticated
}
},
watch: {
isAuthenticated () {
this.$router.push('/calendar')
}
},
methods: {
handleSubmit (formData) {
// Updates isAuthenticated on success
this.$store.dispatch('requestAuthToken', formData)
}
}
3번이나 4번이 가장 좋을까요?가장 깨끗한 느낌이지만 여러분의 생각을 알고 싶습니다:D
미리 시간을 내주셔서 감사합니다!
내 생각에 너는 너의 아이디어 #2를 원하는 것 같아.왜 이런 식으로 하지 않는가?
- 당신이 전화하세요
handleFormSubmit()
에Login.vue
디스패치 대상loginFormSubmit()
액션.로딩 상태를 유효하게 할 수 있습니다.Login.vue
이 시점에서 UX에 대해서. - 사용자가 로그인할 수 있는 경우
getUserProfile()
그렇지 않으면 에러가 표시됩니다.Login.vue
getUserProfile()
API에서 가져오기- 테스트
response
동작 또는 패스 중 하나의 API에서response
다른 돌연변이로 바꿔치기 할 수 있어요 - 사용자에게 프로파일 데이터가 있는 경우 업데이트
state
그리고.router.push('/pathToNews')
,또 다른router.push('/pathToSettings')
다음은 개념을 설명하기 위한 간단한 psuedo 코드입니다.
// store
state: {
userProfile: {}
},
mutations: {
setUserProfile (state, payload) {
state.userProfile = payload
}
},
actions: {
getUserProfile() {
let self = this
axios.get('${API_URL}/token')
.then(function (response) {
// test response against what is expected for a populated profile
if (response.data is a populated user profile) {
self.commit('setUserProfile', response.data)
self.router.push('/news')
} else {
self.router.push('/settings')
}
})
.catch(function (error) {
console.error(error);
// handle your error
})
.finally(function () {
// always executed
})
}
}
개인적으로 리다이렉트/처리 오류에 대해 다음 두 가지 솔루션을 조합하여 사용합니다.
를 사용합니다.
axios
가장 명확한 컷 상태 코드에 대한 인터셉터:import axios from 'axios' axios.interceptors.response.use(response => response, error => { const { status } = error.response const errorMessage = error.response.data.message if (status === Constants.STATUS_CODE_ERROR_NOT_FOUND) { router.push('/404') return } else if (status === Constants.STATUS_CODE_ERROR_UNAUTHENTICATED){ ... } ... }
작업을 확인하고 리디렉션 또는 기타 필요한 작업을 위해 구성 요소를 반환합니다.
다른 점에 유의하십시오.async/await
대신then/catch
.
마이플로우:
- 요소
(this.$store.dispatch('getProfile'...)
- action - 서버(
const response = await fetch ...
) 변환에 대한 응답을 커밋합니다. - 변환 스토어에 정보 저장
- store(모든 정보가 저장되어 있는 유일한 장소)
- 컴포넌트(이것으로부터 데이터를 순서대로 취득합니다).$store.state.user.hasProfile을 사용하여 작업을 결정합니다.)
요약: {login, password} 요청을 보낸 후 서버로부터 {hasProfile: true/false}와 같은 응답을 받습니다.
if(hasProfile) {
// router to
} else {
// router to
}
언급URL : https://stackoverflow.com/questions/44801333/changing-route-from-vuex-actions-and-components
반응형
'programing' 카테고리의 다른 글
JVM, JDK, JRE 및 OpenJDK의 차이점은 무엇입니까? (0) | 2022.07.03 |
---|---|
Vue mapState 비반응 (0) | 2022.07.03 |
메모리 리크 디텍터의 동작 원리 (0) | 2022.07.02 |
int를 4바이트 문자 배열로 변환(C) (0) | 2022.07.02 |
C/C++의 const 어레이와 static const 어레이의 차이점은 무엇입니까? (0) | 2022.07.02 |