itsource

Vuex Store의 작업 내에서 푸시 경로 푸시

mycopycode 2022. 8. 28. 09:55
반응형

Vuex Store의 작업 내에서 푸시 경로 푸시

매장 내에서 경로 변경을 푸시하려고 합니다.Import를 시도했습니다.router매장 자체에서 다음과 같은 일을 할 수 있습니다.

LOG_OUT({commit}){
  commit('LOG_OUT__MUTATION');

  router.push({
   name: 'Login' 
  })
}

하지만 소용없었어요

또한 컴포넌트를 사용하여 직접 루트 변경을 푸시하고 싶지 않습니다.이는 인증을 체크하고 컴포넌트별로 루트 변경을 푸시해야 하기 때문에 번거롭다고 생각되기 때문입니다.

편집 완료:

LOG_OUT__MUTATION는 스테이트에 저장되어 있는 토큰을 클리어합니다.

드디어 알아냈어

최종 실장

고객님의 고객명store를 Import하기만 하면 됩니다.router:

import router from '@/router/index'

actions: {

  LOG_OUT({commit}){
    commit('LOG_OUT__MUTATION');

    router.push({
      name:'Login'
    })
  }

}

그리고 앱의 다른 부분에서는 단순히 Import만 하면 됩니다.store액션을 디스패치했습니다.

import Store from '@/store/store'

myFunction () {
  Store.dispatch('LOG_OUT');
}

초기 구현

다음은 Daksh Miglani의 솔루션 구현(동작)입니다.제 스토어에는 다음과 같은 것이 있었습니다.

export const forceLogout = (commit) => {

  return new Promise((resolve, reject) => {
    commit('LOG_OUT__MUTATION');
    resolve();
  })

}

export default new Vuex.Store({
  actions,
  mutation
})

그리고 앱의 다른 부분(helpers.js)에서는 다음과 같은 기능이 있습니다.

import Store from '@/store/store'
import { forceLogout } from '@/store/store'
import router from '@/router/index'

forceLogout(Store.commit)
  .then(() => {
    debugger;
    router.push({
      name:'Login'
    })

  }).catch((error) => {
     console.log(error)
  })

좋아, 자네를 위한 해결책이 있어

따라서 먼저 다음과 같이 스토어를 커밋하는 함수를 작성합니다.

export const commitLogout = ({commit}) => {
  return new Promise((resolve, reject) => {
    commit('LOG_OUT__MUTATION');
    // once you're done with your clearing, resolve or reject the promise
    resolve();
  });
}

이 함수는 로그아웃 함수로 사용할 수 있는 약속을 반환합니다.이 함수는 마지막에 커밋 및 클리어 후 로그아웃할 수 있습니다.

그런 다음 이 기능을 로그아웃 함수로 사용합니다.

...

  logout() {
    commitLogout().then(() => {
      this.$router.push({
       name: 'Login' 
      })
    })
  }

...

언급URL : https://stackoverflow.com/questions/49064563/push-route-from-within-action-in-vuex-store

반응형