반응형
Vue js 호출 동작 내부 동작
내 Vuex 저장소에 다음 작업이 있음:
import { HTTP } from '@/services/http'
import router from '@/router'
export const actions = {
loginUser ({ commit, state }, params) {
HTTP.post('v1/login.json', { email: params.email, password: params.password })
.then(response => {
localStorage.setItem('access_token', response.data.token)
router.push({name: 'Hello'})
}).catch(error => {
commit('SET_LOGIN_ERROR', error.response.data.error)
})
},
myAccount ({ commit }) {
HTTP.get('v1/my_account.json').headers({'Authorization': ('Token token=' + localStorage.getItem('access_token'))})
.then(response => {
commit('SET_USER', response.data)
})
}
}
출시하고 싶다myAccount
할 때 행동하다.loginUser
성공하다내가 어떻게 그럴 수 있을까?
이런 걸 해봤는데
import { HTTP } from '@/services/http'
import router from '@/router'
export const actions = {
loginUser ({ commit, state }, params) {
HTTP.post('v1/login.json', { email: params.email, password: params.password })
.then(response => {
localStorage.setItem('access_token', response.data.token)
router.push({name: 'Hello'})
}).catch(error => {
commit('SET_LOGIN_ERROR', error.response.data.error)
})
},
myAccount ({ dispatch, commit, state }, payload) {
dispatch('loginUser', payload)
.then((res) => {
console.log('dupa')
// Do this when loginUser finished
})
}
}
하지만 이건 효과가 없어...
행동을 받다.context
객체: 전체 객체를 통과하거나 파괴 할당에 디스패치를 추가하십시오.
const store = new Vuex.Store({
actions: {
foo(context) {
console.log('foo called');
},
bar({dispatch}) {
setTimeout(() => dispatch('foo'), 1000)
}
}
});
여기 JSFiddle: https://jsfiddle.net/y1527vxh/
vue 작업은 비동기적일 수 있으므로 작업이 완료되면 다른 작업을 호출하기 위해 작업에 디스패치 핸들러를 추가할 수 있다.
export const actions = {
loginUser ({ commit, state }, params) {
... // some http request or what would you like to do
},
myAccount ({ dispatch, commit, state }, payload) {
dispatch('loginUser', payload)
.then((res) => {
...
// Do this when loginUser finished
})
},
}
나는 이런 프로젝트에서 자동화를 하고 있어, 나는 공리 btw:
loginUser ({ dispatch, commit, state }, payload) {
let loginData = {
username: payload.username,
password: payload.password
}
return axios.post(state.url, loginData)
.then((res) => {
// You can console.log(res.data) to see if your token data is fine
window.localStorage.setItem('AuthTokens', JSON.stringify(res.data))
dispatch('myAccount', { tokens: res.data })
})
.catch((err) => {
// Error handling...
})
},
myAccount ({ commit, state }, { tokens }) {
let headerOptions = {
// Header options with tokens.access_token...
}
return axios.get(state.url, headerOptions)
.then((res) => {
// You have the user data
console.log(res.data)
})
.catch((err) => {
// Error handling...
})
}
참조URL: https://stackoverflow.com/questions/46873996/vue-js-calling-action-inside-action
반응형
'programing' 카테고리의 다른 글
bootstrap-vue: 특정 css 가져오기 (0) | 2022.05.02 |
---|---|
C에서 열거형의 크기는 얼마인가? (0) | 2022.05.02 |
Java 파일 크기 가져오기 (0) | 2022.05.02 |
서명되지 않은 정수 오버플로가 정의된 동작은 정의되지만 서명된 정수 오버플로는 정의되지 않는 이유는? (0) | 2022.05.02 |
C에서 문자 숫자를 해당하는 정수로 변환 (0) | 2022.05.02 |