IT이야기

vue 앱의 main.js 파일에서 스토어 getter 업데이트 값에 액세스하는 방법

cyworld 2022. 3. 19. 12:11
반응형

vue 앱의 main.js 파일에서 스토어 getter 업데이트 값에 액세스하는 방법

다음 사이트에서 업데이트된 Vuex Getter에 액세스하려고 함main.js사용자가 로그인했는지 여부를 확인하는 파일.이에 따라 사용자를 로그인 페이지로 이동시킨다.main.js 파일에서 나는 단지 이렇게 가게게터에 접속한다.

var router = new VueRouter({...})

router.beforeEach((to, from, next) => {
    console.log(store.getters['general/isUserLoggedIn'])
    next()
})

general은 모듈 이름이다.

그러나 단순히 로그에 기록하면 업데이트된 값을 가진 객체가 표시된다.하지만 로깅할 때는store.getters['general/isUserLoggedIn']초기 상태 값을 나타낸다.왜 그것이 업데이트된 가치를 제공하지 않는지.그것이 올바른 행동 방식인가 아니면 다른 방법이 있는가?

자세한 내용

store.js 파일로

import Vue from 'vue'
import Vuex from 'vuex'
import general from './modules/general'
import other from './modules/other'

Vue.use(Vuex)

export const store = new Vuex.Store({
    modules: {
        general,
        other
    },
    plugins: [],
    strict: process.env.NODE_ENV !== 'production'
})

App.vue 파일에서 api status를 호출하여 로그인한 사용자 확인

axios.get('/api/profile').then((response) => {
    if (response.data.status === 'success') {
        this.setUserLoggedIn(true)
    }
})

일반 모듈의 actions.js

setUserLoggedIn ({ commit }, data) {
    commit(types.SET_USER_LOGGED_IN, data)
}

일반 모듈에서의 muttions.js

const mutations = {
    [types.SET_USER_LOGGED_IN](state, data) {
        state.isUserLoggedIn = data
    }
}

초기 탐색에서 가드에는 아직 로그인이 완료되지 않았으므로 콘솔에서 값을 볼 수 없다.단지 나타난다.true로깅할 때store로그 직후에 설정되며, 개체/로그인을 로그에 기록한 다음 클릭하여 해당 속성을 볼 때 콘솔이 자체 업데이트되기 때문이다.

경기 조건을 해결하는 한 가지 방법은 로그인이 완료되면 홈 페이지로 리디렉션하는 것이다.

axios.get('/api/profile').then((response) => {
  if (response.data.status === 'success') {
    this.setUserLoggedIn(true)
    this.$router.push('/');  // Route to home page once login is complete
  }
})

그 전에 사용자가 로그인하지 않은 경우 로그인으로 리디렉션하십시오.

router.beforeEach((to, from, next) => {
  const isLoggedIn = store.getters['general/isUserLoggedIn'];
  if(!isLoggedIn) {
    return next('/login');
  }
  next()
})
  • 초기 로드 시 사용자는 로그인 페이지로 리디렉션된다.
  • 로그인이 완료되면, 그들은 홈페이지로 다시 보내질 것이다.

참조URL: https://stackoverflow.com/questions/66347258/how-to-access-store-getter-updated-value-from-main-js-file-in-vue-app

반응형